繁体   English   中英

将数组从服务传递到控制器

[英]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

的jsfiddle

.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM