4

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});
    }
});

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

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.

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?

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
  • Which browser are you using? I know in Chrome; if you expand/drill into an object the value of the object's properties will be the value a the time of expansion not the time of the log. Have you tried stepping through code? – JeffryHouser Apr 01 '14 at 04:09

2 Answers2

7

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();
})
Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
0

I agree with above answer but still in some cases like on input of text box,

you need to give timer to digest it properly.

setTimeout(function(){
    $scope.apply();
}, 50);

This solves my problem.

Rahul
  • 18,271
  • 7
  • 41
  • 60