In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller’s constructor function. A new child scope will be available as an injectable parameter to the Controller’s constructor function as $scope.
javascript
在Angular里,控制器就是一个用来加强Scope的JavaScript的构造函数。 当一个控制器经过ng-controller指令被附在DOM上的时候,Angular就会用这个指定的构造函数,初始化一个新的控制器实例。同时,1个子scope会以$scope的名字的变量身份,被注入到新的构造函数里。 php
Typically, when you create an application you need to set up the initial state for the Angular $scope. You set up the initial state of a scope by attaching properties to the $scope object. The properties contain the view model (the model that will be presented by the view). All the $scope properties will be available to the template at the point in the DOM where the controller is registered.
css
照理说,每当你建立一个应用的时候,你须要为$scope设置初始化状态。怎么设置?就是给$scope上挂一些属性。这些属性包含不少展现模型(view model)(就是给前面的view展现的模型model)。全部挂在$scope下的属性,对于DOM上对应的这个控制器下的模板都是可见的(就是说,你要是在html里挂了这个controller,js里定义给这个controller的全部$scope下的属性啊,方法啊,就均可以调用了)。html
The following example demonstrates creating a GreetingController, which attaches a greeting property containing the string 'Hola!' to the $scope:java
举个栗子: react
1 var myApp = angular.module('myApp', []); 2 myApp.controller('GreetingController', ['$scope', function($scope) { 3 $scope.greeting = 'Hola!'; 4 }]);
名叫GreetingController的控制器里,$scope下面挂了个属性greeting,值是'Hola!'。(西语的Hello,感受本身萌萌哒)nginx
We create an Angular Module, myApp, for our application. Then we add the controller's constructor function to the module using the .controller() method. This keeps the controller's constructor function out of the global scope.express
We have used an inline injection annotation to explictly specify the dependency of the Controller on the $scope service provided by Angular.
apache
咱们为咱们的这个应用建立了一个Angular里大名鼎鼎的模块(Module),叫myApp。而后咱们用.controller()把控制器的构造函数添进了这个模块里去。这样作就是不想让控制器的构造函数变成全局变量。django
We attach our controller to the DOM using the ng-controller directive. The greeting property can now be data-bound to the template:
1 <div ng-controller="GreetingController"> 2 {{ greeting }} 3 </div>
而后就是用ng-controller把控制器挂DOM上,你看,绑定的数据能够用了。
In order to react to events or execute computation in the view we must provide behavior to the scope. We add behavior to the scope by attaching methods to the $scope object. These methods are then available to be called from the template/view.
The following example uses a Controller to add a method, which doubles a number, to the scope:
1 var myApp = angular.module('myApp', []); 2 myApp.controller('DoubleController', ['$scope', function($scope) { 3 $scope.double = function(value) { return value * 2; }; 4 }]);
Once the Controller has been attached to the DOM, the double method can be invoked in an Angular expression in the template:
1 <div ng-controller="DoubleController"> 2 Two times <input ng-model="num"> equals {{ double(num) }} 3 </div>
As discussed in the Concepts section of this guide, any objects (or primitives) assigned to the scope become model properties. Any methods assigned to the scope are available in the template/view, and can be invoked via angular expressions and ng event handler directives (e.g. ngClick).
看代码样例便可
In general, a Controller shouldn't try to do too much. It should contain only the business logic needed for a single view.
The most common way to keep Controllers slim is by encapsulating work that doesn't belong to controllers into services and then using these services in Controllers via dependency injection.
一般状况下,不要在控制器里干太多事。控制器里的业务逻辑应该只为1个单一的视图服务。
最多见的保持控制器内容最少的方法,是把不属于控制器的工做封装到服务里去,而后在控制器里经过依赖注入来调用。
You can associate Controllers with scope objects implicitly via the ngController directive or $route service.
To illustrate further how Controller components work in Angular, let's create a little app with the following components:
A template with two buttons and a simple message
A model consisting of a string named spice
A Controller with two functions that set the value of spice
The message in our template contains a binding to the spice model which, by default, is set to string "very". Depending on which button is clicked, the spice model is set to chili or jala, and the message is automatically updated by data-binding.
index.html:
1 <div ng-controller="SpicyController"> 2 <button ng-click="chiliSpicy()">Chili</button> 3 <button ng-click="jalaSpicy()">Jala</button> 4 <p>The food is {{ spice }} spicy!</p> 5 </div>
app.js:
1 var myApp = angular.module('spicyApp1', []); 2 myApp.controller('SpicyController', ['$scope', function($scope) { 3 $scope.spice = "very"; 4 $scope.chiliSpicy = function() { 5 $scope.spice = "chili"; 6 }; 7 $scope.jalaSpicy = function() { 8 $scope.spice = "jala"; 9 }; 10 }]);
Things to notice in the example above:
The ng-controller directive is used to (implicitly) create a scope for our template, and the scope is augmented (managed) by the SpicyController Controller.
SpicyController is just a plain JavaScript function. As an (optional) naming convention the name starts with capital letter and ends with "Controller".
Assigning a property to $scope creates or updates the model.
Controller methods can be created through direct assignment to scope (see the chiliSpicy method)
The Controller methods and properties are available in the template (for both the <div> element and its children).
这个例子里值得注意的地方:
ng-controller指令会为模板生成一个scope,而后这个scope就由这个叫作SpicyController的控制器来监管;
咱们有个命名规范(你不必定要遵照)就是:控制器都大写开头,屁股上挂Controller结尾;
给$scope的属性赋值的话,会建立一个model(这样前面的template就能够用了),若是这货已经存在,那就是更新它的值;
控制器的方法能够直接挂在$scope下
控制器里的方法和属性均可以在模板上调用(so easy)
Controller methods can also take arguments, as demonstrated in the following variation of the previous example.
index.html:
1 <div ng-controller="SpicyController"> 2 <input ng-model="customSpice"> 3 <button ng-click="spicy('chili')">Chili</button> 4 <button ng-click="spicy(customSpice)">Custom spice</button> 5 <p>The food is {{spice}} spicy!</p> 6 </div>
app.js:
1 var myApp = angular.module('spicyApp2', []); 2 myApp.controller('SpicyController', ['$scope', function($scope) { 3 $scope.customSpice = 'wasabi'; 4 $scope.spice = 'very'; 5 $scope.spicy = function(spice) { 6 $scope.spice = spice; 7 }; 8 }]);
.... .... .... ....
It is common to attach Controllers at different levels of the DOM hierarchy. Since the ng-controller directive creates a new child scope, we get a hierarchy of scopes that inherit from each other. The $scope that each Controller receives will have access to properties and methods defined by Controllers higher up the hierarchy.
咱们常常在DOM的不一样位置挂载控制器。既然控制器能够建立子scope,显然(由于DOM是树状的),咱们就有了一个树状结构的scope们。每一个控制器拿到本身的$scope的时候,它也就能够访问比这个scope更高的scope下的属性和方法。
index.html:
1 <div class="spicy"> 2 <div ng-controller="MainController"> 3 <p>Good {{timeOfDay}}, {{name}}!</p> 4 <div ng-controller="ChildController"> 5 <p>Good {{timeOfDay}}, {{name}}!</p> 6 <div ng-controller="GrandChildController"> 7 <p>Good {{timeOfDay}}, {{name}}!</p> 8 </div> 9 </div> 10 </div> 11 </div>
app.css:
1 div.spicy div { 2 padding: 10px; 3 border: solid 2px blue; 4 }
app.js:
1 var myApp = angular . module ( 'scopeInheritance' , []); 2 myApp . controller ( 'MainController' , [ '$scope' , function ( $scope ) { 3 $scope . timeOfDay = 'morning' ; 4 $scope . name = 'Nikki' ; 5 }]); 6 myApp . controller ( 'ChildController' , [ '$scope' , function ( $scope ) { 7 $scope . name = 'Matti' ; 8 }]); 9 myApp . controller ( 'GrandChildController' , [ '$scope' , function ( $scope ) { 10 $scope . timeOfDay = 'evening' ; 11 $scope . name = 'Gingerbread baby' ; 12 }]);
Notice how we nested three ng-controller directives in our template. This will result in four scopes being created for our view:
The root scope
The MainController scope, which contains timeOfDay and name properties
The ChildController scope, which inherits the timeOfDay property but overrides (hides) the name property from the previous
The GrandChildController scope, which overrides (hides) both the timeOfDay defined in MainController and the name property defined in ChilidController
Inheritance works with methods in the same way as it does with properties. So in our previous examples, all of the properties could be replaced with methods that return string values.
继承对方法也是有效的,跟它对于属性的影响是同样同样的。因此,上面的例子虽然都写的是属性,换成方法照样管用。