[英]Passing an array from service to controller
I cannot seem to figure out how to pass an array from service to a controller. 我似乎无法弄清楚如何将数组从服务传递到控制器。
I have a simple service 我的服务很简单
.service('test', function() {
var array = []
return array;
})
And a controller where I call this function when a button is pressed 还有一个控制器,当我按下按钮时,我会调用此函数
$scope.testArray = function() {
$scope.test = test.array;
console.log("test: ", $scope.test);
};
I get an error test is undefined. 我得到一个错误测试未定义。 Can anyone explain to me please why this doesn't work and how to fix it?
谁能向我解释为什么这个方法不起作用以及如何解决? I tried storing that array in a separate object but no luck either.
我尝试将该数组存储在单独的对象中,但也没有运气。 THanks
谢谢
(See also: this SO question about Angular providers ) (另请参见: 有关Angular提供程序的此SO问题 )
A service
should put properties directly on this
. service
应直接在this
属性上。 So instead of 所以代替
.service('test', function() {
var array = [];
return array;
})
try 尝试
.service('test', function() {
this.array = [];
})
(code style notwithstanding; many would suggest preferring function access over direct object access) (尽管使用了代码样式;许多建议使用函数访问而不是直接对象访问)
.service('test', function() {
var array = [];
this.getArray = function(){
return array;
};
})
Add the array
variable to your service
. 将
array
变量添加到您的service
。
angular.module('moduleName').service('test', function() {
this.array = [];
});
Inject your service
into your controller
. 将
service
注入controller
。
angular.module('moduleName').controller('controllerName', function(test) {
$scope.test = test.array;
console.log("test: ", $scope.test);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.