使用角度控制器,能够使用在角度控制器外声明的数组的最佳方法是什么?
首先我声明一个数组:
var cars = ["Saab", "Volvo", "BMW"];
我还有一个角度控制器:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
});
我试过了:
将变量作为参考传递给控制器:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope, url) {
});
并且只是尝试从控制器中调用变量:
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
console.log(cars[1]);
});
然而,两者都没有奏效。
我如何实现这一目标?
答案 0 :(得分: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:
(into #{} (map inc) #{1 2 3})
then you could inject that service into your controller like this:
var ListService = (function () {
function ListService() {
this.cars = ["", "", ""]
}
return ListService;
})();
myApp.service("listService", [ListService]);