[英]Passing an array from service to controller
我似乎无法弄清楚如何将数组从服务传递到控制器。
我的服务很简单
.service('test', function() {
var array = []
return array;
})
还有一个控制器,当我按下按钮时,我会调用此函数
$scope.testArray = function() {
$scope.test = test.array;
console.log("test: ", $scope.test);
};
我得到一个错误测试未定义。 谁能向我解释为什么这个方法不起作用以及如何解决? 我尝试将该数组存储在单独的对象中,但也没有运气。 谢谢
(另请参见: 有关Angular提供程序的此SO问题 )
service
应直接在this
属性上。 所以代替
.service('test', function() {
var array = [];
return array;
})
尝试
.service('test', function() {
this.array = [];
})
(尽管使用了代码样式;许多建议使用函数访问而不是直接对象访问)
.service('test', function() {
var array = [];
this.getArray = function(){
return array;
};
})
只需使用test
更改test.array
:
.controller('youCtrl', ['$scope', 'test', function ($scope, test) {
$scope.testArray = function() {
$scope.test = test;
console.log("test: ", $scope.test);
};
});
将array
变量添加到您的service
。
angular.module('moduleName').service('test', function() {
this.array = [];
});
将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.