Mastering Web Application

(Rick Simeone) #1

Packaging and Deploying AngularJS Web Applications


Defining controllers for directives needs a bit of attention as the syntax might be
surprising at first. Here is an example of the accordion directive (also discussed in
Chapter 9, Building Advanced Directives) that defines a controller as follows:


.directive('accordion', function () {
return {
restrict:'E',
controller:['$scope', function ($scope) {
// This array keeps track of the accordion groups
this.groups = [];

}],
link: function(scope, element, attrs) {
element.addClass('accordion');

}
};
})

The pitfalls of array-style DI annotations

While array-style DI annotations make the AngularJS-specific code minification
safe, they do so at the price of code duplication. Indeed, we need to list arguments
of the function twice: in the function definition and in the array. As with any code
duplication, this one can be problematic, especially when refactoring existing code.


It is relatively easy to forget a new argument and omit it in the annotation array, or
mix the order of arguments in two places as shown in the following example:


angular.module('app')
.config(['$locationProvider', '$routeProvider', function
($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.otherwise({redirectTo:'/projectsinfo'});
}]);

Writing DI-annotations requires concentration, as errors resulting from incorrect
annotating are hard to track down.

Free download pdf