6

In angular.js, $scope.greeting = xxx doesn't work in window.setTimeout. It has not any effect:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
    $scope.greeting = 'init';
    window.setTimeout(function () {
        console.log('update greeting');
        $scope.greeting = "hello"; // doesn't work here.
    }, 3000);
})

Why?

The full comparison is below:

3 Answers 3

16

setTimeout operates outside of the $digest cycle - therefore angular doesn't know about the change that you applied to $scope.

Instead of window.setTimeout, use the built in $timeout function

See this (your) updated jsfiddle here

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use $scope.$apply within your setTimeout. But $timeout is definitely better.
4

I think you must use special service from angular

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope, $timeout) {
    $scope.greeting = 'init';
    $timeout(function(){
        $scope.greeting = "hello";
    }, 2000);
})

Comments

0

In this case, (as mentioned in answers) you can use $timeout instead of setTimeout. But in all cases you can use $scope.$apply() to change the $scope that is outside of the $digest cycle.

window.setTimeout(function () {
    $scope.greeting = "hello";
    $scope.$apply();
}, 3000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.