I have a question for the angularjs folks here.
So, I am using angular for quite a while now. However, every time when I am writing a new Controller or something that is using dependency injection, I find myself miswriting the the inline definition.
someModule.controller('MyController', ['dep1', 'dep2', function (dep1, dep2) {
...
}]);
I understand how it works, but why did the angular guys not decide for a more common approach? For example the requirejs way
someModule.controller('MyController', ['dep1', 'dep2'], function(dep1, dep2) {
...
});
What is bothering me, is that the second argument is a array of dependencies and the callback as the last element at the same time. In fact, the whole module code is written in the last array element.
Wouldn't it be better to have the dependencies in an extra array? This way we could easily pass a array of dependencies dynamically into a definition.
I find this rather awkward but never really thought about the reason behind. Can someone explain this to me?
I don't know the actual reason behind this syntax, but I assume it has to do with consistency --you should be able to use the same syntax regardless of where you need to inject services.
Most places use the syntax in your example: module.controller
, module.factory
etc. In those places the syntax could bee like requirejs.
However, when defining a directive you can also inject services into its controller. This is usually done if the directive's controller will be used by other directives, e.g. the ngModel
directive.
module.directive('myDirective', function () {
return {
controller: ['$scope', '$element', function ($scope, $element) {
// ...
}]
};
});
In this case you can't use the requirejs style, but the array style works. I guess this could be one of the reasons the syntax is as it is. There might be others.
As a side note you could define the directive's controller as a normal controller, but this makes the code more verbose, plus you could potentially use the controller in other places than the directive.
module.controller('myDirectiveCtrl', ['$scope', '$element', function ($scope, $element) {
// ...
}]);
And then define the directive.
module.directive('myDirective', function () {
return {
controller: 'myDirectiveCtrl'
};
});
You don't have to use the syntax with an array anymore. You can write your code like this:
module.directive('myDirective', function () {
return {
controller: function ($scope, $element) {
// ...
}
}
});
Read more here