【发布时间】:2014-03-29 03:56:29
【问题描述】:
无法弄清楚此代码中的错误是什么。我已尝试仅在此处发布代码的相关部分。
控制器
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();
});
});
我的通知 Angular 服务
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>
问题:
使用控制台日志和使用业力测试我已经确认,当我从 Notification Service 执行 $broadcast 时,MessageCtrl 中的 $rootScope.$on 方法会被调用。并且msgCount 变量正在增加。但是,我没有看到更新的值反映在 不运行 $scope.$digest() 的模板中。我很确定我不需要调用 $scope.$digest ,即 Angular 应该为我提供这个绑定。
有趣的是,当我从另一个控制器尝试$rootScope.$broadcast 时,模板中的msgCount 会递增,而无需调用$scope.$digest()。
任何人都可以在这里帮助我。谢谢你。
更新
感谢 Peter 并查看了 google 小组讨论,将 $broadcast 包装在 $apply 中就成功了。
$rootScope.$apply(function(){
$rootScope.$broadcast('pubnub:question', m);
});
【问题讨论】:
标签: angularjs angularjs-scope pubnub