我有一个名为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
,请问任何建议的解决方案?
答案 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));