我有两个角度控制器都有这个:
var data = ['one', 'two', 'three', 'four'];
如何在一个地方而不是两个地方拥有它并在每个控制器中重复使用它?
答案 0 :(得分:1)
您可以创建一个包含返回数组
的方法的服务app.service('myService', function() {
var data = ['one', 'two', 'three', 'four'];
this.getData= function () {
return data;
}
});
并在控制器内调用
app.controller('myCtrl', function($scope, myService) {
$scope.data = myService.getData();
});
答案 1 :(得分:1)
这样做的正确方法是使用value
或constant
providers,这样做就是为了做到这一点。然后,您可以在您拥有的任何其他提供者声明(即directive
,component
,controller
等)上注入此内容。
myApp.value('MyData', ['one', 'two', 'three', 'four']);
myApp.controller('myController', function (MyData) {
var $ctrl = this;
$ctrl.data = MyData;
});
答案 2 :(得分:0)
这个数组是简单的模型数据表示,你应该把它放到服务中(服务是单例,在每个控制器中你都可以访问同一个数组)。
简单示例:
app.factory('myArray',
function() {
this.array = ['one', 'two', 'three', 'four'];
return this.array;
});
在每个控制器中,您都可以访问此阵列:
app.controller('myCtrl', function($scope, myArray) {
$scope.array = myArray;
});
可用的Plunker示例https://plnkr.co/edit/m307rP4IjcXSJpPWmHeA?p=info