smk*_*smk 3 angularjs pubnub angularjs-scope
无法弄清楚这段代码中的错误是什么.我试图只在这里发布代码的相关部分.
调节器
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();
});
});
Run Code Online (Sandbox Code Playgroud)
我的通知角度服务
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;
}]);
Run Code Online (Sandbox Code Playgroud)
和模板:
<div>
Count = {{msgCount}}
</div>
Run Code Online (Sandbox Code Playgroud)
问题:
使用控制台日志和使用karma测试我已经确认当我从Notification Service 执行时调用该$rootScope.$on方法.并且变量正在增加.但是,我没有看到更新的值在没有运行的情况下反映在模板中.我很确定我不需要打电话 ,即Angular应该为我提供这种绑定.MessageCtrl$broadcastmsgCount$scope.$digest()$scope.$digest
有趣的是,当我尝试使用$rootScope.$broadcast另一个控制器时,msgCount模板中的内容增加而不必调用$scope.$digest().
任何人都可以在这里帮助我.谢谢.
更新
感谢彼得并看了谷歌小组的讨论,包装了$broadcast一个$apply诀窍.
$rootScope.$apply(function(){
$rootScope.$broadcast('pubnub:question', m);
});
Run Code Online (Sandbox Code Playgroud)
Pet*_*nko 10
看来你的问题$broadcast发生在AngularJS之外,你需要通过调用通知你的应用程序有关它$apply(),但最好在它中进行notificationService.
至于$ broadcast和$ on触发申请/摘要,你可以在这篇文章中阅读.AngularJs源文件的简要概述让我确保$ broadcast不会自动应用更改(请看这里).$ broadcast只是呼叫听众,没有别的.
请看一下这个关于jsFiddle的简单例子.
该模板
<div ng-controller="myCtrl">
<p>Count: {{ count }}</p>
<button ng-click="fireEvent()">Fire Event</button>
</div>
Run Code Online (Sandbox Code Playgroud)
该控制器
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);
};
})
Run Code Online (Sandbox Code Playgroud)
和工厂
.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;
}]);
Run Code Online (Sandbox Code Playgroud)
当然,在这两种情况下,你都会看到事件监听器触发,但是ngClick会触发$ digest,而你notificationService却没有.
你也可以在这个很好的答案中获得一些关于将启动摘要的来源的信息/sf/answers/874393481/
| 归档时间: |
|
| 查看次数: |
22406 次 |
| 最近记录: |