View not updating after changing $scope variable

To simplify the problem I have:

.controller(‘DashCtrl’, function($scope) {
$scope.message = “a”;
setTimeout(function() {
$scope.message = “b”;
}, 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?

I managed to solve it after reading this article:

Thank you Mr Hoskins.

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


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

.controller('DashCtrl', function($scope) {
    $ = { message: "a" };
    setTimeout(function() {
        $ = "b";
    }, 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);

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) {
$scope.message = msg;
socket.on(‘msgin’, function (data) {
msg =data.msg;
$scope.$apply(function(){$scope.message = msg;});

1 Like

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.

Thanks @cys . That saved my day

1 Like

thanks man.!
i was facing that problem routinely…

Simply awesome, what I was looking it was exact result.