【问题标题】:Angular Service can set data from one controller but not the otherAngular Service 可以从一个控制器设置数据,但不能从另一个控制器设置数据
【发布时间】:2015-10-22 13:31:35
【问题描述】:

我有一个模块和两个控制器:

var module = angular.module("app", ["agGrid", "ngAnimate", "ngSanitize", "ngDialog"])


module.controller("mainCtrl", ["$scope", "dataService","$timeout","dateFilter","ngDialog", "$http", function ($scope, $http, $timeout, dateFilter, ngDialog, dataService) {
}]);


module.controller("modalCtrl", ["$scope", "ngDialog", "dataService", function ($scope, ngDialog, dataService) {


$scope.printEntity = function () {
    console.log(dataService.getEntityArray());
}

}]);

还有一项服务:

 module.factory("dataService", function () {

var entityArrayService = [];

return {
    setEntityArray: function (entityArray) {
        entityArrayService = entityArray;
    },
    getEntityArray: function () {
        return entityArrayService;
    }

};

});

我可以从我的 SECOND 控制器内部调用 dataService.setEntityArray(array),但是当我尝试从我的第一个控制器调用它时,它告诉我 dataService.setEntityArray is not a function

【问题讨论】:

    标签: javascript html angularjs service controller


    【解决方案1】:

    依赖注入的顺序不正确。控制器函数中的参数必须重复数组中元素的顺序。在您的情况下,dataService 是第二个参数:

    module.controller("mainCtrl", ["$scope", "dataService","$timeout","dateFilter","ngDialog", "$http", function ($scope, dataService, $timeout, dateFilter, ngDialog, $http) {
    }]);
    

    【讨论】:

    • 你在开玩笑,顺序很重要!?谢谢!时间用完会接受。
    • 当然 :) 这就是数组表示法的要点,以便 Angular 知道什么参数对应于什么服务。这样当它是['dataService', '$http', function(a, b) {}] 时,Angular 就知道aDataService,等等。
    • 哦,我明白了!感谢您的帮助!
    【解决方案2】:

    您在第一个控制器定义中的变量顺序无效。应该是:

    function ($scope, dataService, $timeout, dateFilter, ngDialog, $http)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2018-06-15
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多