簡體   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