码迷,mamicode.com
首页 > 其他好文 > 详细

学习控制器

时间:2015-08-27 21:04:30      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

Understanding Controllers (控制器)

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.

Use controllers to:

  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.

Do not use controllers to:

  • Manipulate DOM ---- Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has data binding for most cases and directives to encapsulate manual DOM manipulation.
  • Format input ---- Use angular form controls instead.
  • Filter output ---- Use angular filters instead.
  • Share code or state across controllers ---- Use angular services instead.
  • Manage the life-cycle of other components (for example, to create service instances).

在Angular里,控制器就是一个用来增强Scope的JavaScript的构造函数。 当一个控制器通过ng-controller指令被附在DOM上的时候,Angular就会用这个指定的构造函数,初始化一个新的控制器实例。同时,1个子scope会以$scope的名字的变量身份,被注入到新的构造函数里。

这些情况下你应该使用控制器:

  • 设置$scope对象初始化状态的时候;
  • 向$scope对象添加行为的时候。

这些情况你不应该使用控制器:

  • 操纵DOM的时候 ---- 控制器里就应该只有业务逻辑。任何把展示的逻辑放进控制器的行为,都会大大影响其可测试性。几乎所有情况下,操纵DOM的操作都可以被数据绑定和指令完成;
  • 格式化输入 ---- 用Angular提供的表单控制吧;
  • 过滤输出 ---- 用Angular的过滤器不是很棒?
  • 在控制器间共享代码和状态 ---- 用Angular的服务好吗?
  • 管理其它组件的生命周期 (比方说创建服务实例)


Setting up the initial state of a $scope object

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.

照理说,每当你创建一个应用的时候,你需要为$scope设置初始化状态。怎么设置?就是给$scope上挂一些属性。这些属性包含很多展示模型(view model)(就是给前面的view展示的模型model)。所有挂在$scope下的属性,对于DOM上对应的这个控制器下的模板都是可见的(就是说,你要是在html里挂了这个controller,js里定义给这个controller的所有$scope下的属性啊,方法啊,就都可以调用了)。

The following example demonstrates creating a GreetingController, which attaches a greeting property containing the string ‘Hola!‘ to the $scope:

举个栗子: 

1 var myApp = angular.module(‘myApp‘, []);
2 myApp.controller(‘GreetingController‘, [‘$scope‘, function($scope) {
3     $scope.greeting = ‘Hola!‘;
4 }]);

名叫GreetingController的控制器里,$scope下面挂了个属性greeting,值是‘Hola!‘。(西语的Hello,感觉自己萌萌哒)

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.

We have used an inline injection annotation to explictly specify the dependency of the Controller on the $scope service provided by Angular.

我们为我们的这个应用创建了一个Angular里大名鼎鼎的模块(Module),叫myApp。然后我们用.controller()把控制器的构造函数添进了这个模块里去。这样做就是不想让控制器的构造函数变成全局变量。

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上,你看,绑定的数据可以用了。

Adding Behavior to a Scope Object

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). 

给Scope对象添加行为(就是可调用的方法/函数嘛)

看代码样例即可




Using Controllers Correctly

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个单一的视图服务。

最常见的保持控制器内容最少的方法,是把不属于控制器的工作封装到服务里去,然后在控制器里通过依赖注入来调用。

Associating Controllers with Angular Scope Objects

You can associate Controllers with scope objects implicitly via the ngController directive or $route service.

Simple Spicy Controller Example(这个例子很简单,看代码即可)

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)

Spicy Arguments Example (可以传参的一个例子)

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 }]);

.... .... .... ....

Scope Inheritance Example

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. 

Scope继承的例子

我们经常在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.

继承对方法也是有效的,跟它对于属性的影响是一样一样的。所以,上面的例子虽然都写的是属性,换成方法照样管用。



学习控制器

标签:

原文地址:http://www.cnblogs.com/amile1860/p/4518395.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!