Building and Testing
angular.module('admin-projects').controller('ProjectsEditCtrl',
function($scope) {
//controller's code goes here
});
We've managed to eliminate the extra variable but our code didn't get any better.
Can you notice how the angular.module('admin-projects') is repeated all over
the place All code duplication is evil and this one can hit us hard, if we decide to
rename a module one day. On top of this the syntax to declare a new module and to
retrieve an existing one can be easily mistaken leading, to very confusing results. Just
compare the angular.module('myModule') with angular.module('myModule',
[]). It is easy to overlook the difference, isn't it?
It is better to avoid retrieving AngularJS modules using the angular.
module('myModule') construct. The syntax is verbose and results
in code duplication. Worse yet, module's declaration can be easily
confused with accessing instances of an existing module.
Luckily there is one more approach that addresses all the problems described so far.
Let's have a look at the code first:
angular.module('admin-projects', [])
.controller('ProjectsListCtrl', function($scope) {
//controller's code go here
})
.controller('ProjectsEditCtrl', function($scope) {
//controller's code go here
});
We can see that it is possible to chain calls to the controller's registration logic.
Each call to the controller method will return an instance of a module on which
the method was invoked. Other provider-registering methods (factory, service,
value, and so on) are returning a module's instance, as well so it is possible to
register different providers using the same pattern.
In our sample SCRUM application we are going to use the chaining syntax just
described to register all the providers. This way of registering providers eliminates the
risk of creating superfluous (potentially global!) variables and avoids code duplication.
It is also very readable provided that some effort is put into code formatting.