Thursday, 5 September 2013

Is there a way to declare a controller in AngularJS and only specify its dependencies once?

Is there a way to declare a controller in AngularJS and only specify its
dependencies once?

In order to keep dependency injection working after minification I'm using
this style to declare a controller:
myModule.controller('myController', ['$rootScope', 'Service',
function($rootScope, Service) {
$scope.foo = 'bar';
}]);
Let's say you want to add another service. You'd have to add it in 2
places, in the array preceding the controller function, and as a parameter
of the controller function itself. My question is, is there a way to make
this DRY-er? Could you declare a dependency array and use that to build
the outer array and the inner parameters, something like this?:
var dependencies = ['$rootScope', 'Service'];
var myProtoController = function() {
$scope.foo = 'bar';
};
var myController = dependencies.push(myProtoController.bind.apply(this,
[this].concat(dependencies)));
myModule.controller('myController', myController);

No comments:

Post a Comment