javascript
3、Angular JS 学习笔记 – Controllers [翻译中]
2019獨角獸企業重金招聘Python工程師標準>>>
理解控制器
在Angular中,一個控制器是一個javascript構造函數用于填充Angular作用域。
當一個控制器通過使用ng-controller指令附加到DOM上的時候,Angular將初始化一個新的Controller對象,使用指定的控制器構造函數。一個新的子作用域將可以作為一個參數$scope被注入到控制器構造函數。
控制器用于:
- 配置作用域對象的初始化狀態
- 添加行為到作用域對象
不要將控制器用于:
- 維護DOM - 控制器應該只包含業務邏輯。放置任何的展現邏輯到控制器中將極大的影響可測試性。
- 格式化輸入 - 應該使用angular表單控制器處理
- 過濾輸出 - 應該使用angular過濾器處理
- 在多個控制器中共享代碼或狀態 - 應該使用angular service。
建立作用域對象的初始化狀態
通常,當你創建一個應用你必須設置Angular作用域的初始化狀態。你通過附加屬性到$scope對象去設置作用域初始化狀態。這些屬性包括視圖模型(這個模型將通過視圖呈現)。作用域中的所有屬性都將提供給在dom中注冊了控制器的模板。
下面的例子演示了創建一個GreetingController,附加一個包含字符串'Hola!'的屬性到作用域上。
var myApp = angular.module('myApp',[]);myApp.controller('GreetingController', ['$scope', function($scope) {$scope.greeting = 'Hola!'; }]);我們創建一個Angular模塊名稱為myApp為我們的應用。然后我們添加控制器構造函數到模塊,使用.controller方法。這樣兒是保持控制器構造函數不放在全局作用域中。
我們使用一個行內注入標記去明確的聲明Controller的依賴于Angular 提供的$scope服務。查看手冊 Dependency Injection了解更多的信息。我們附加我們的控制器到DOM使用ng-controller指令,greeting屬性現在就可以數據綁定到模板了。
<div ng-controller="GreetingController">{{ greeting }} </div>添加行為到作用域對象
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 to the scope, which doubles a number:
var myApp = angular.module('myApp',[]); myApp.controller('DoubleController', ['$scope', function($scope) { $scope.double = function(value) { return value * 2; }; }]);Once the Controller has been attached to the DOM, the double method can be invoked in an Angular expression in the template:
<div ng-controller="DoubleController">Two times <input ng-model="num"> equals {{ double(num) }} </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).
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. This is discussed in the Dependency Injection Services sections of this guide.
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 the string "very". Depending on which button is clicked, the spice model is set to chili or jalape?o, and the message is automatically updated by data-binding.
? Edit in Plunker index.html app.js <div ng-controller="SpicyController"><button ng-click="chiliSpicy()">Chili</button><button ng-click="jalapenoSpicy()">Jalape?o</button><p>The food is {{spice}} spicy!</p> </div>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 theSpicyController 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 the <div> element and its children).
Spicy Arguments Example
Controller methods can also take arguments, as demonstrated in the following variation of the previous example.
? Edit in Plunker index.html app.js <div ng-controller="SpicyController"><input ng-model="customSpice"><button ng-click="spicy('chili')">Chili</button><button ng-click="spicy(customSpice)">Custom spice</button><p>The food is {{spice}} spicy!</p> </div>Notice that the SpicyController Controller now defines just one method called spicy, which takes one argument called spice. The template then refers to this Controller method and passes in a string constant 'chili' in the binding for the first button and a model property customSpice (bound to an input box) in the second button.
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. See Understanding Scopes for more information about scope inheritance.
? Edit in Plunker index.html app.css app.js <div class="spicy"><div ng-controller="MainController"><p>Good {{timeOfDay}}, {{name}}!</p><div ng-controller="ChildController"><p>Good {{timeOfDay}}, {{name}}!</p><div ng-controller="GrandChildController"><p>Good {{timeOfDay}}, {{name}}!</p></div></div></div> </div>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 property defined in MainController and the nameproperty defined in ChildController
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.
Testing Controllers
Although there are many ways to test a Controller, one of the best conventions, shown below, involves injecting the $rootScope and$controller:
Controller Definition:
var myApp = angular.module('myApp',[]); myApp.controller('MyController', function($scope) { $scope.spices = [{"name":"pasilla", "spiciness":"mild"},{"name":"jalapeno", "spiciness":"hot hot hot!"},{"name":"habanero", "spiciness":"LAVA HOT!!"}]; $scope.spice = "habanero"; });Controller Test:
describe('myController function', function() { describe('myController', function() {var $scope; beforeEach(module('myApp')); beforeEach(inject(function($rootScope, $controller) { $scope = $rootScope.$new(); $controller('MyController', {$scope: $scope});})); it('should create "spices" model with 3 spices', function() { expect($scope.spices.length).toBe(3);}); it('should set the default value of spice', function() { expect($scope.spice).toBe('habanero');});}); });If you need to test a nested Controller you need to create the same scope hierarchy in your test that exists in the DOM:
describe('state', function() {var mainScope, childScope, grandChildScope; beforeEach(module('myApp')); beforeEach(inject(function($rootScope, $controller) { mainScope = $rootScope.$new(); $controller('MainController', {$scope: mainScope}); childScope = mainScope.$new(); $controller('ChildController', {$scope: childScope}); grandChildScope = childScope.$new(); $controller('GrandChildController', {$scope: grandChildScope});})); it('should have over and selected', function() { expect(mainScope.timeOfDay).toBe('morning'); expect(mainScope.name).toBe('Nikki'); expect(childScope.timeOfDay).toBe('morning'); expect(childScope.name).toBe('Mattie'); expect(grandChildScope.timeOfDay).toBe('evening'); expect(grandChildScope.name).toBe('Gingerbread Baby');}); });tips:
本文由wp2Blog導入,原文鏈接:http://devonios.com/3%e3%80%81angular-js-%e5%ad%a6%e4%b9%a0%e7%ac%94%e8%ae%b0-controllers.html
轉載于:https://my.oschina.net/yangyan/blog/859235
總結
以上是生活随笔為你收集整理的3、Angular JS 学习笔记 – Controllers [翻译中]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Zookeeper的多节点集群详细启动步
- 下一篇: Spring中Bean的后置处理器