Not able to figure out what the bug in this code is.I've tried to only post the relevant parts of the code here.
Controller
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();
});
});
My Notification Angular Service
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;
}]);
And the template :
<div>
Count = {{msgCount}}
</div>
The problem :
Using console logs & using karma tests I have confirmed that the $rootScope.$on
method in MessageCtrl
is getting called when I do a $broadcast
from Notification Service. And that the msgCount
variable is getting incremented. However, I don't see the updated value being reflected in the template without running a $scope.$digest()
. I am pretty sure I shouldn't be needing to have to call $scope.$digest
, ie Angular should be providing me this binding.
Interestingly, when I tried a $rootScope.$broadcast
from another controller, the msgCount
in the template got incremented without having to call $scope.$digest
().
Can anyone kindly help me here. Thank you.
Update
Thanks to Peter and looking at the google group discussion, wrapping the $broadcast
in an $apply
did the trick.
$rootScope.$apply(function(){
$rootScope.$broadcast('pubnub:question', m);
});