RSM
RSM

Reputation: 15108

best way to access javascript array from angular controller

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?

Upvotes: 2

Views: 111

Answers (1)

Nicholas J. Markkula
Nicholas J. Markkula

Reputation: 1562

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])

Upvotes: 1

Related Questions