Vous êtes sur la page 1sur 7

Controllers

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.

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. The following example shows a very simple constructor function for a Controller, GreetingCtrl, which attaches a greeting property containing the string 'Hola!' to the $scope:
1. function GreetingCtrl($scope) { $scope.greeting = 'Hola!'; } 2. <div ng-controller="GreetingCtrl">{{ greeting }}</div>

NOTE: Although Angular allows you to create Controller functions in the global scope, this is not recommended. In a real application you should use the .controller method of your Angular Module for your application as follows. We have used an inline injection annotation to explicitly specify the dependency of the Controller on the $scope service provided by Angular.
1. var myApp = angular.module('myApp',[]); 2. myApp.controller('GreetingCtrl', ['$scope', function($scope) { 3. $scope.greeting = 'Hola!'; 4. }]);

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 to the scope, which doubles a number. Once the Controller has been attached to the DOM, the double method can be invoked in an Angular expression in the template.

1. 2. 3. 4. 5. 6. 7.

var myApp = angular.module('myApp',[]); myApp.controller('DoubleCtrl', ['$scope', function($scope) { $scope.double = function(value) { return value * 2; }; }]); <div ng-controller="DoubleCtrl"> Two times <input ng-model="num"> equals {{ double(num) }} </div>

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. Do not use Controllers for: Any kind of DOM manipulation Controllers should contain only business logic. DOM manipulation (the presentation logic of an application) is well known for being hard to test. Putting any presentation logic into Controllers significantly affects testability of the business logic. Angular offers databinding for automatic DOM manipulation. If you have to perform your own manual DOM manipulation, encapsulate the presentation logic in directives. Input formatting Use angular form controls instead. Output filtering Use angular filters instead. Sharing stateless or stateful code across Controllers Use angular services instead. Managing the life-cycle of other components (for example, to create service instances).

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 jalapeo, and the message is automatically updated by data-binding.
index.html
1. <!doctype html> 2. <html ng-app="spicyApp1"> 3. <head> 4. <script src="http://code.angularjs.org/1.2.7/angular.min.js"></script> 5. <script src="script.js"></script> 6. </head> 7. <body> 8. <div ng-app="spicyApp1" ng-controller="SpicyCtrl"> 9. <button ng-click="chiliSpicy()">Chili</button> 10. <button ng-click="jalapenoSpicy()">Jalapeno</button> 11. <p>The food is {{spice}} spicy!</p> 12. </div> 13. </body> 14. </html>

script.js
1. var myApp = angular.module('spicyApp1', []); 2. myApp.controller('SpicyCtrl', ['$scope', function($scope){ 3. $scope.spice = 'very'; 4. $scope.chiliSpicy = function() { $scope.spice = 'chili'; }; 5. $scope.jalapenoSpicy = function() { $scope.spice = 'jalapeno'; }; 6. }]);

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 SpicyCtrl Controller. SpicyCtrl is just a plain JavaScript function. As an (optional) naming convention the name starts with capital letter and ends with "Ctrl" or "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.
index.html
1. <!doctype html> 2. <html ng-app="spicyApp2"> 3. <head>

4. <script src="http://code.angularjs.org/1.2.7/angular.min.js"></script> 5. <script src="script.js"></script> 6. </head> 7. <body> 8. <div ng-app="spicyApp2" ng-controller="SpicyCtrl"> 9. <input ng-model="customSpice"> 10. <button ng-click="spicy('chili')">Chili</button> 11. <button ng-click="spicy(customSpice)">Custom spice</button> 12. <p>The food is {{spice}} spicy!</p> 13. </div> 14. </body> 15. </html>

script.js
1. var myApp = angular.module('spicyApp2', []); 2. myApp.controller('SpicyCtrl', ['$scope', function($scope){ 3. $scope.customSpice = "wasabi"; 4. $scope.spice = 'very'; 5. $scope.spicy = function(spice){ $scope.spice = spice; }; 6. }]);

Notice that the SpicyCtrl 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 ngcontroller 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.
index.html
1. <!doctype html> 2. <html ng-app="scopeInheritance"> 3. <head> 4. <script src="http://code.angularjs.org/1.2.7/angular.min.js"></script> 5. <script src="script.js"></script> 6. </head> 7. <body> 8. <div ng-app="scopeInheritance" class="spicy"> 9. <div ng-controller="MainCtrl"> 10. <p>Good {{timeOfDay}}, {{name}}!</p> 11. 12. <div ng-controller="ChildCtrl"> 13. <p>Good {{timeOfDay}}, {{name}}!</p> 14. 15. <div ng-controller="GrandChildCtrl"> 16. <p>Good {{timeOfDay}}, {{name}}!</p> 17. </div> 18. </div> 19. </div> 20. </div>

21. </body> 22. </html>

script.js
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. var myApp = angular.module('scopeInheritance', []); myApp.controller('MainCtrl', ['$scope', function($scope){ $scope.timeOfDay = 'morning'; $scope.name = 'Nikki'; }]); myApp.controller('ChildCtrl', ['$scope', function($scope){ $scope.name = 'Mattie'; }]); myApp.controller('GrandChildCtrl', ['$scope', function($scope){ $scope.timeOfDay = 'evening'; $scope.name = 'Gingerbreak Baby'; }]);

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 MainCtrl scope, which contains timeOfDay and name properties The ChildCtrl scope, which inherits the timeOfDay property but overrides (hides) the name property from the previous The GrandChildCtrl scope, which overrides (hides) both the timeOfDay property defined in MainCtrl and the name property defined in ChildCtrl

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:
1. var myApp = angular.module('myApp',[]); 2. 3. myApp.controller('MyController', function($scope) { 4. $scope.spices = [{"name":"pasilla", "spiciness":"mild"}, 5. {"name":"jalapeno", "spiceiness":"hot hot hot!"}, 6. {"name":"habanero", "spiceness":"LAVA HOT!!"}]; 7. $scope.spice = "habanero"; 8. });

Controller Test:
1. describe('myController function', function() { 2. 3. describe('myController', function() { 4. var $scope;

5. 6. beforeEach(module('myApp')); 7. 8. beforeEach(inject(function($rootScope, $controller) { 9. $scope = $rootScope.$new(); 10. $controller('MyController', {$scope: $scope}); 11. })); 12. 13. it('should create "spices" model with 3 spices', function() { 14. expect($scope.spices.length).toBe(3); 15. }); 16. 17. it('should set the default value of spice', function() { 18. expect($scope.spice).toBe('habanero'); 19. }); 20. }); 21. });

If you need to test a nested Controller you need to create the same scope hierarchy in your test that exists in the DOM:
1. describe('state', function() { 2. var mainScope, childScope, grandChildScope; 3. 4. beforeEach(module('myApp')); 5. 6. beforeEach(inject(function($rootScope, $controller) { 7. mainScope = $rootScope.$new(); 8. $controller('MainCtrl', {$scope: mainScope}); 9. childScope = mainScope.$new(); 10. $controller('ChildCtrl', {$scope: childScope}); 11. grandChildScope = childScope.$new(); 12. $controller('GrandChildCtrl', {$scope: grandChildScope}); 13. })); 14. 15. it('should have over and selected', function() { 16. expect(mainScope.timeOfDay).toBe('morning'); 17. expect(mainScope.name).toBe('Nikki'); 18. expect(childScope.timeOfDay).toBe('morning'); 19. expect(childScope.name).toBe('Mattie'); 20. expect(grandChildScope.timeOfDay).toBe('evening'); 21. expect(grandChildScope.name).toBe('Gingerbreak Baby'); 22. }); 23. });

Filters
A filter formats the value of an expression for display to the user. They can be used in view templates, controllers or services and it is easy to define your own filter. The underlying API is the filterProvider.

Using filters in view templates


Filters can be applied to expressions in view templates using the following syntax:
{{ expression | filter }}

E.g. the markup {{ 12 | currency }} formats the number 12 as a currency using the currency filter. The resulting value is $12.00. Filters can be applied to the result of another filter. This is called "chaining" and uses the following syntax:
{{ expression | filter1 | filter2 | ... }}

Filters may have arguments. The syntax for this is


{{ expression | filter:argument1:argument2:... }}

E.g. the markup {{ 1234 | number:2 }} formats the number 1234 with 2 decimal points using the number filter. The resulting value is 1,234.00.

Using filters in controllers and services


You can also use filters in controllers and services. For this, add a dependency with the name <filterName>Filter to your controller or service. E.g. using the dependency numberFilter will inject the number filter. The injected argument is a function that takes the value to format as first argument and filter parameters starting with the second argument.

The example below uses the filter called filter. This filter reduces arrays into sub arrays based on conditions. The filter can be applied in the view template with markup like {{ctrl.array | filter:'a'}}, which would do a fulltext search for "a". However, using a filter in a view template will reevaluate the filter on every digest, which can be costly if the array is big.

The example below therefore calls the filter directly in the controller. By this, the controller is able to call the filter only when needed (e.g. when the data is loaded from the backend or the filter expression is changed).

Vous aimerez peut-être aussi