Ryan Ryan - 23 days ago 8
AngularJS Question

How can I reuse a hardcoded array of data in multiple angular 1.5 controllers?

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?

Answer

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;
});