2014-03-29 98 views
3

无法弄清楚此代码中的错误是什么。我试过只在这里发布代码的相关部分。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> 

问题

使用控制台日志&使用因缘测试中,我已经证实,当我从通知服务做$broadcastMessageCtrl$rootScope.$on方法获取调用。并且msgCount变量正在递增。但是,我没有看到更新的值反映在模板中,而没有运行 a $scope.$digest()。我很确定我不应该需要呼叫$scope.$digest,即Angular应该为我提供这种绑定。

有趣的是,当我从另一个控制器尝试$rootScope.$broadcast时,模板中的msgCount增加了,而不必调用$scope.$digest()。

任何人都可以在这里帮助我。谢谢。

更新 感谢彼得看着谷歌的小组讨论,包裹在$apply$broadcast奏效了。

$rootScope.$apply(function(){ 
         $rootScope.$broadcast('pubnub:question', m); 
        }); 

回答

9

看来你$broadcast外面发生和AngularJS你需要调用$apply()通知你的应用程序有关,但做的更好的notificationService

至于$广播和$触发申请/摘要,你可以在this post阅读。 AngularJs源文件的简要概述使我确信$广播不会自动应用更改(look here)。 $广播只是调用监听器,没有别的。

请看看jsFiddle上的这个简单例子。

模板

<div ng-controller="myCtrl"> 
    <p>Count: {{ count }}</p> 
    <button ng-click="fireEvent()">Fire Event</button> 
</div> 

控制器

angular.module("app", []) 
.controller('myCtrl', function($scope, $rootScope, notificationService) { 
    $scope.count = 0; 
    notificationService.subscribe(); 
    $rootScope.$on('event', function() { 
     console.log("event listener"); 
     $scope.count++; 
    }); 

    $scope.fireEvent = function() { 
     // it is ok here due to ngClick directve 
     $rootScope.$broadcast('event', true); 
    }; 
}) 

而且工厂

.factory('notificationService',['$rootScope', function($rootScope) { 

    var notificationService = { 
     subscribe : function() { 
      setInterval(function(){ 
       console.log("some event happend and broadcasted"); 
       $rootScope.$broadcast('event', true); 
       // angular does not know about this 
       //$rootScope.$apply(); 
      }, 5000); 
     } 
    }; 
    return notificationService; 
}]); 

当然在这两种情况下,您都会看到事件侦听器触发,但ngClick触发$摘要,而您的notificationService则不触发。

此外,你可以得到一些信息源将启动摘要cicle在这个很好的答案https://stackoverflow.com/a/12491335/1274503