Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Data One Step Behind

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?

like image 584
Sterling Archer Avatar asked Mar 20 '23 01:03

Sterling Archer


1 Answers

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();
})
like image 149
Anthony Chu Avatar answered Mar 27 '23 15:03

Anthony Chu