I came across different coding style using Angularjs and it made me think what the advantage and disadvantage of each coding style.
eg. Declaring of controllers:
Style #1 means the controllers are defined outside of the module as globals, alright for small test projects but for any serious work, everything should be done using #2 or #3. The difference between #2 and #3 is #3 is minifiable as the $scope and $rootScope names in #2 will normally be optimised out, which causes the application to fail. #3 Stores these as strings which will not be minified out.
If there's at least a possibility that you'll be minifying your code, go for #3. There's very little point in using #1 over #2 so I tend to avoid #1 altogether.
All of them are valid, but exposing global functions is usually not a good idea (names can clash), sot it is better to have the functions encapsulated in angular's own domain.
This makes style #2.
AngularJS uses dependency injection
to provide other services, filters, controllers etc. This is done by peeking the function parameters, getting them via regex and providing them as necessary.
But, what happens when you minify? To get rid of extra bytes, the minifiers rename the variables and parameters within the function, since it not change anything and everything would work if we were not peeking to get the parameters of the function.
When minified, e.g. $rootScope
becomes a
, and it will throw an error like there is no aProvider
, yeah that's right.
So, angular has another syntax, it is the array notation; instead of defining a function, you can define an array which has the dependency names followed by the implementing function.
So,
angular.controller("MainCtrl", ["$scope", "$routeParams", function (a,b) {
// a == $scope
// b == $routeParams
}]);
There are also other ways to do it, instead of defining an array. You can set the function's $inject property to an array.
function MainCtrl(a,b) {
// a == $scope
// b == $routeParams
}
MainCtrl.$inject = ["$scope", "$routeParams"];
For further info: http://docs.angularjs.org/guide/di