更新数组时,AngularJS会更新HTML

时间:2015-06-05 09:16:08

标签: javascript angularjs

我有这种情况,在HTML上我使用ng-repeat="user in controller.users"在我的页面上显示用户。

在JS中我有:

Main.leaderboard(function(res) {
        vm.users = res;
    }, function() {
        $rootScope.error = 'Failed to fetch details';
    });

此后,当用户注册时,我正在使用套接字实时显示在页面上:

    socket.on('player joined', function(data) {
        console.log('player ' + data.username +' joined');
        vm.users.push(data);
    });

我尝试过使用$ digest但非常有效,它会返回

  

未捕获的TypeError:vm.users。$ digest不是一个函数(匿名   功能)

有人可以解释当vm.users更新时如何更新HTML吗?

2 个答案:

答案 0 :(得分:0)

问题是套接字是出自Angular的世界"。

正如Pankajparkar所说,把它放在Angular的世界里#34;使用$timeout

socket.on('player joined', function(data) {
    $timeout( function(){ // $timeout is part of Angular. You don't need to give it a delay.
        vm.users.push(data); // Now Angular is aware of that.
    });
});

为了使用$ timeout,你需要将它注入你的控制器:

myApp.controller('mainCtrl', function ($scope, $timeout){...

答案 1 :(得分:0)

您需要使用$timeout功能,以确保您的摘要能够在不与其他正在运行的摘要周期冲突的情况下运行。

socket.on('player joined', function(data) {
    $timeout(function(){
        console.log('player ' + data.username +' joined');
        vm.users.push(data);
    })
});

注意

  

不要忘记在控制器中添加$timeout依赖项