Вопрос

This is a nooob question - as in I started learning Angular today. I was following the tutorial at Angular JS in 30 mins

The idea is to setup basic databinding in Angular. The code displays an input box, and shows(updates) whatever is typed in the box adjacent to it. Coming from a Java world and Spring MVC background, it makes perfect sense as long as the code is as follows:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test Angular</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="maincontroller.js"></script>
</head>
<body>
 <div id="content" ng-app="SampleAngular" ng-controller="MainController">
  <input type="text" ng-model="inputVal">{{ inputVal }}
 </div>
</body>
</html>

app.js

var app = angular.module('SampleAngular', []);

maincontroller.js

app.controller("MainController", function($scope){
$scope.inputVal = "";

}
);

But, the same thing still works if I have a blank body for the controller i.e.:

maincontroller.js

app.controller("MainController", function($scope){


}
);

I understand that I will not be able to get the value of inputVal in the controller but

a) why does it still work in the view? b) Clearly, I don't have a corresponding model 'inputVal' as defined in ng-model directive, and there are no errors/warnings - which IMHO - is equivalent to failing silently. Is this how Angular is designed? Is this a potential issue in large apps and will make debugging a nightmare?

Thanks in advance.

Это было полезно?

Решение

The following is from the api documentation for ngModel:

Note: ngModel will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope.

Другие советы

Whenever a ng-model is used in the view, corresponding model value is created on the scope of the controller. Angular won't be throwing any error in this case, as this is its default behaviour.

$scope.inputVal = "";

is used more like initialisation of the variable being used.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top