2

What is the best way to be able to use an array declared outside of an angular controller, withing the angular controller?

first I declare an array:

var cars = ["Saab", "Volvo", "BMW"];

I also have an angular controller:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {


});

I have tried:

Passing the variable through as reference in the controller:

var myApp = angular.module('myApp', []);

    myApp.controller('MyCtrl', function ($scope, url) {


    });

and simply trying to call the variable from within the controller:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {

console.log(cars[1]);
});

However, neither have worked.

How do I achieve this?

2
  • You may want to create the resource and then inject it, I think this may be of help: stackoverflow.com/questions/30133415/… Commented May 12, 2015 at 22:11
  • If the array doesn't change (i.e. it's a fixed list of car types). I would use an Angular constant. You can inject those just like services, except it's not an object. It's just data you inject. So it'll remain an array type. Commented May 13, 2015 at 1:23

1 Answer 1

1

Typically I would use an angular service. https://docs.angularjs.org/guide/services

You could create a service that contains the list like this:

var ListService = (function () {
    function ListService() {
        this.cars = ["", "", ""]
    }       
    return ListService;
})();
myApp.service("listService", [ListService]);

then you could inject that service into your controller like this:

var MyCtrl = function ($scope, listService) {
    console.log(listService.cars[1]);
}
myApp.controller('MyCtrl', ['$scope', 'listService', MyCtrl])
Sign up to request clarification or add additional context in comments.

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.