AngularJS数据落后一步 [英] AngularJS Data One Step Behind

查看:64
本文介绍了AngularJS数据落后一步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angularJS跟踪地图坐标以更新数据,但是遇到一个奇怪的问题,即您在屏幕上看到的数据与console语句不匹配.

I'm tracking map coordinates using angularJS to update the data, however I've run into an odd issue where the data you see on the screen does not match the console statement.

zombie.controller("move", function($scope) {
    io.on("location", function(data) {
        console.log(data);
        $scope.location = data.loc;
    })
    $scope.move = function(direction) {
        $scope.title = ": Traveling";
        io.emit("move", {direction:direction});
    }
});

控制台将记录以下内容:Object {loc: "(59,30)"}

The console will log something like: Object {loc: "(59,30)"}

让我们假设以前的数据是Object {loc: "(60,31)"}.控制台登录(59,30)时,我的页面将显示(60,31).

Let's assume the previous data was Object {loc: "(60,31)"}. My page will print (60,31) when the console is logging (59,30).

此外,在页面加载时,初始单击将不显示任何内容,但控制台将记录正确的数据.

Also, when the page loads, the initial click will not display anything, but the console will log the correct data.

我曾尝试在角度函数内部移动io.on('location'),但是如果它在move()内部,它将摇摇欲坠并连续记录15次,并退出.除此问题外,该功能还可以.有什么想法吗?

I have tried moving io.on('location') around inside the angular function, but if it's inside move() it will go bonkers and log like 15 times in a row and lag out. Outside the function is fine except for this issue. Any thoughts?

推荐答案

io.on("location")中的代码是由socket.io启动的,而Angular对此并不了解,因此直到下一个摘要循环.这可能是屏幕更新始终落后一步的原因.使用$scope.$apply()强制摘要...

The code inside the io.on("location") is initiated by socket.io and Angular doesn't know about it, so its changes to the scope are not reflected until the next digest cycle. That is likely why the screen updates are always one step behind. Use $scope.$apply() to force a digest...

io.on("location", function(data) {
    console.log(data);
    $scope.location = data.loc;
    $scope.$apply();
})

这篇关于AngularJS数据落后一步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆