javascript - AngularJs + Pubnub 数据绑定(bind)

标签 javascript angularjs pubnub ng-bind

我使用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/

相关文章:

javascript - Node readline 接口(interface)以乘法方式重复每个字符

javascript - 如何回避变量定义中的 no-use-before-define let foo = foo || [];?

php - 使用 jquery、ajax 和 php 将 div 中更新的数据保存到数据库

javascript - pubnub存储和播放历史记录功能

javascript - 关于动态添加 PubNub channel 的查询

javascript - 复杂拆分正则表达式

angularjs - 如何以 Angular 扩展 $http 服务?

javascript - 此模型中的 AngularJS ng-repeat

javascript - 如何使用 Javascript/AngularJs 将按钮放置在图像上的特定位置(x,y)

android - 后台应用程序在 Titanium 中不接收来自 pubnub for android 的消息