在控制器中随机将工厂值更改为null,但是我将其注入控制器

时间:2015-08-28 18:10:58

标签: angularjs service controller inject

我有一个名为myController的控制器,如下所示:

'use strict';

app.controller('myController', ['$rootScope', '$scope', 'myService',
 function ($rootScope, $scope, myService) { 
     $scope.myService = myService;

     $rootScope.$on('kpi:submit', function (event, data) {
            $window.sessionStorage['prevCall'] = JSON.stringify(data.prevCall);
            $window.sessionStorage['currCall'] = JSON.stringify(data.currentCall);
            $window.sessionStorage['nextCall'] = JSON.stringify(data.nextCall);

            myService.prevCall = $scope.prevCall = data.prevCall;
            myService.currentCall = $scope.currentCall = data.currentCall;
            myService.nextCall = $scope.nextCall = data.nextCall;
     });
}]);

以及myService工厂,如下所示:

'use strict';

app.factory('myService', ['$http', '$q', function ($http, $q) {     
        this.currentCall;
        this.prevCall;
        this.nextCall;

        // some function
        return {
            myFunction : myFunction
        };
}]);

当我点击kpi:submit按钮时,系统会调用Submit。它运行良好,但有时我得到以下错误:

TypeError: Cannot set property 'prevCall' of null

那么,为什么myService工厂突然变为null,请问任何建议的解决方案?

1 个答案:

答案 0 :(得分:0)

您传入$rootScope.$broadcast的匿名函数没有对myService的引用。

注入你的功能:

function (event, data, myService)

继续使用$ scope:

$scope.myService.prevCall = $scope.prevCall = data.prevCall;

也可以使用bind:

 $rootScope.$on('kpi:submit', function (event, data) {

 }.bind(myService));

Angular.bind(var, function);

相关问题