【问题标题】:Passing an array from service to controller将数组从服务传递到控制器
【发布时间】:2015-09-05 16:44:52
【问题描述】:

我似乎不知道如何将数组从服务传递到控制器。

我有一个简单的服务

.service('test', function() {
    var array = []

    return array;
})

还有一个控制器,我在按下按钮时调用此函数

$scope.testArray = function() {
    $scope.test = test.array;

    console.log("test: ", $scope.test);
};

我得到一个错误测试未定义。谁能向我解释一下为什么这不起作用以及如何解决?我尝试将该数组存储在一个单独的对象中,但也没有运气。谢谢

【问题讨论】:

  • 您是否将服务注入您的控制器?
  • 是的,这是我的控制器 -> .controller('TestCtrl', ['test', function(test) {

标签: javascript angularjs model-view-controller service


【解决方案1】:

(另见:this SO question about Angular providers

service 应该将属性直接放在this 上。所以不是

.service('test', function() {
    var array = [];

    return array; 
})

试试

.service('test', function() {
    this.array = [];
})

(尽管有代码风格;许多人会建议更喜欢函数访问而不是直接对象访问)

.service('test', function() {
    var array = [];
    this.getArray = function(){
        return array;
    };
})

【讨论】:

  • 非常感谢!我就像你在上一个例子中展示的那样,然后尝试了 console.log(test.getArray());它有效!你能告诉我为什么我的解决方案不起作用,而这个功能解决了它吗?
【解决方案2】:

只需将test.array更改为test

JSFiddle

.controller('youCtrl', ['$scope', 'test', function ($scope, test) {
    $scope.testArray = function() {
       $scope.test = test;

       console.log("test: ", $scope.test);
    };
});

【讨论】:

  • 试过这个,对我不起作用。我可能已经跳闸了,如果可能的话,它是 Ionic 应用程序的一部分。
  • 谢谢大家,现在它也可以工作了,这个返回对象给我和数组上方的建议,所以两者都很好。谢谢!
【解决方案3】:

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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    相关资源
    最近更新 更多