无法弄清楚此代码中的错误是什么。我试过只在这里发布代码的相关部分。AngularJs变量未更新
控制器
myApp.controller('MessageCtrl', function ($scope, notificationService, $rootScope) {
$scope.notificationService = notificationService;
$scope.msgCount = 0;
$scope.notificationService.subscribe({channel : 'my_channel'});
$rootScope.$on('pubnub:msg',function(event,message){
$scope.msgCount = $scope.msgCount + 1;
//$scope.$digest();
});
});
我的通知角服务
myApp.factory('notificationService',['$rootScope', function($rootScope) {
var pubnub = PUBNUB.init({
publish_key : '..',
subscribe_key : '..'
});
var notificationService = {
subscribe : function(subscription) {
pubnub.subscribe({
channel : subscription.channel,
message : function(m){
$rootScope.$broadcast('pubnub:msg', m);
}
});
}
};
return notificationService;
}]);
而且模板:
<div>
Count = {{msgCount}}
</div>
问题:
使用控制台日志&使用因缘测试中,我已经证实,当我从通知服务做$broadcast
在MessageCtrl
的$rootScope.$on
方法获取调用。并且msgCount
变量正在递增。但是,我没有看到更新的值反映在模板中,而没有运行 a $scope.$digest()
。我很确定我不应该需要呼叫$scope.$digest
,即Angular应该为我提供这种绑定。
有趣的是,当我从另一个控制器尝试$rootScope.$broadcast
时,模板中的msgCount
增加了,而不必调用$scope.$digest
()。
任何人都可以在这里帮助我。谢谢。
更新 感谢彼得看着谷歌的小组讨论,包裹在$apply
的$broadcast
奏效了。
$rootScope.$apply(function(){
$rootScope.$broadcast('pubnub:question', m);
});