View not updating after changing $scope variable


#1

To simplify the problem I have:

.controller(‘DashCtrl’, function($scope) {
$scope.message = “a”;
console.log($scope.message);
setTimeout(function() {
$scope.message = “b”;
console.log($scope.message)
}, 8000);
})

The first console.log($scope.message) prints out "a"
The second console.log($scope.message) prints out "b"
However the view remains unchanged showing “a”

What is the issue? Is the second $scope.message assignment creating a different namespace?

How do I get the view to update?


#2

I managed to solve it after reading this article:

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Thank you Mr Hoskins.

I’ll just leave this here for anyone else with the same problem.


#3

You could do it without $apply by defining a global object that holds the variables instead of a global variable:

.controller('DashCtrl', function($scope) {
    $scope.data = { message: "a" };
    console.log($scope.data.message);
    
    setTimeout(function() {
        $scope.data.message = "b";
        console.log($scope.data.message)
    }, 8000);
})

Also, I suggest you do not use setTimeout, but use $timeout instead, because setTimeout ignores the Angular digest cycle:

.controller('DashCtrl', function($scope, $timeout) {

    //..
    $timeout(function() {
        //..
    }, 8000);
}

#4

Thanks so much :smile:

The actual code that I am using to trigger a change to the $scope after a Socket.IO event is received. In this instance, $apply seems to work (though not the neatest code), I couldn’t get it to work with the global object.

.controller(‘DashCtrl’, function($scope) {
msg=“start”
$scope.message = msg;
console.log($scope.message);
socket.on(‘msgin’, function (data) {
msg =data.msg;
$scope.$apply(function(){$scope.message = msg;});
});
})


#5

Sorry for necromancer, but I though it was good to clear this point.

I can’t see global variables in your example. I think global variables are made with $rootScope. Maybe you meant another thing. I just point it because maybe someone come here and get confused with global/local variables.


#6

Thanks @cys . That saved my day


#7

thanks man.!
i was facing that problem routinely…