Reputation: 19896
Let say I have 50 controllers and 25 of them need the same initialization code which is somewhat long such as:
$scope.a = 1;
$scope.b = "a";
...
$scope.zzz = "xyz";
What is the best way? I don't want to copy and paste in each beginning of 25 controllers? I don't want to put in 25 of the views' ng-init
either.
UPDATE 1
I am using angular-ui-router
and each controller is per state per view/template. Maybe there is a way to do this in the angular-ui-router
more DRY?
Upvotes: 0
Views: 46
Reputation: 16300
You can use prototypal inheritance. Think of it like having a base or abstract class, that your other classes inherit from.
var BaseCtrl = function($scope) {
$scope.a = 1;
...
});
var AnotherCtrl = function($scope) {
BaseCtrl.call(this, $scope);
....
});
AnotherCtrl.prototype = Object.create(BaseCtrl.prototype, {});
The syntax would be a little different if you are using ControllerAs.
Upvotes: 0
Reputation: 991
Looks like your project will be going big someday.
I suggest the best way is to use a Class.js like library.
Create a .init() and .destroy() to all objects that will be created.
Upvotes: 0
Reputation: 7666
The service example what I mentioned can be achieved like this:
angular.service('yourService',function() {
return {
setInitialValues: function(scope) {
scope.a = 22;
//All your Initial values
}
}
});
And in the controller inject the services and pass your scope to the controller and set it over their. This will work in the scope of Angular and nothing is global over here
Upvotes: 1
Reputation: 1198
You simply declare a function
var f = function($scope) {
//Init stuff here
}
Then use it in all 25 controlers writen under this text.
//controler1 init..... f($scope);
Upvotes: 0