I have two angular controllers that both have this:
var data = ['one', 'two', 'three', 'four'];
How can I have that in one place instead of two and reuse it in each controller?
I have two angular controllers that both have this:
var data = ['one', 'two', 'three', 'four'];
How can I have that in one place instead of two and reuse it in each controller?
The proper way to do that is by using the value or constant providers, they were designed to do that. Then you can inject this on any of other provider declaration that you have (i.e., directive, component, controller, etc).
myApp.value('MyData', ['one', 'two', 'three', 'four']);
myApp.controller('myController', function (MyData) {
var $ctrl = this;
$ctrl.data = MyData;
});
You can create a service that contains a method that returns the array
app.service('myService', function() {
var data = ['one', 'two', 'three', 'four'];
this.getData= function () {
return data;
}
});
And call it inside your controller
app.controller('myCtrl', function($scope, myService) {
$scope.data = myService.getData();
});
This array is simple model-data representation, and you should put it in to service (service is singleton, and in each controller you have access to same array).
Simple example:
app.factory('myArray',
function() {
this.array = ['one', 'two', 'three', 'four'];
return this.array;
});
In each controller you can access this array:
app.controller('myCtrl', function($scope, myArray) {
$scope.array = myArray;
});
Plunker example available https://plnkr.co/edit/m307rP4IjcXSJpPWmHeA?p=info