我使用Pubnub提供的PubNub+AngularJS脚本文件.我有一个 Controller 可以设置 channel 并订阅它。我在回调函数中设置了范围变量,我看到范围函数中正在更新的值。问题是这个刚刚更新的范围变量没有反射(reflect)在 html 页面中。 控制台输出说 pubnub 消息调用了回调方法,我得到了消息。但由于某种原因,变量数据没有反射(reflect)到 html 中。 这是代码:
TitleBarController.js
$scope.ops_tl = new Object();
$scope.ops_tl.data = new Array();
$scope.ops_tl.data.push("dummy");
console.log("pp ", $scope.ops_tl==undefined);
PubNub.ngSubscribe({ channel: channelsToAutoSubscribe[0] });
$rootScope.$on(PubNub.ngMsgEv(channelsToAutoSubscribe[0]), function(event, payload) {
// payload contains message, channel, env...
console.log('got a message event:', payload);
if(payload.channel == channelsToAutoSubscribe[0]) {
// i.e. ops_tl channel
// parse message and populate channel specific variable
console.log($scope.ops_tl.data);
$scope.ops_tl.data.push(payload.message);
console.log($scope.ops_tl.data);
}
else {
console.log("Received message %s from an unknown channel %s", message, channel);
}
});
index.html
<div class="btn-group" ng-controller="TitleBarController">
<button data-toggle="dropdown" class="btn dropdown-toggle">
New users -
<span> {{ ops_tl.data.length }} </span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li ng-repeat="item in ops_tl.data"><a href="#/onboarding/{{ item.data.id }}">New user - {{ item.data.name }}</a></li>
</ul>
</div>
最佳答案
您遇到的问题与 Angular 中事件循环的处理方式有关。您需要做的是将作用域变量的赋值推迟到事件循环中的新滴答中。执行此操作的最简单方法是利用 $timeout Angular 服务。
尝试改变这一行:
$scope.ops_tl.data.push(payload.message);
对此:
$timeout(function() {
$scope.ops_tl.data.push(payload.message);
});
关于javascript - AngularJs + Pubnub 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33912563/