0

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?

1
  • Have it in service and access it through calling service from both controllers Commented Nov 14, 2016 at 10:14

3 Answers 3

1

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;
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.