Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: update $scope doesn't work in setTimeout callback

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:

  • It works (in ajax): http://jsfiddle.net/victorwoo/eDb2S/129/
  • It doesn't work (in window.setTimeout): http://jsfiddle.net/victorwoo/3b3s6ukp/2/
like image 515
victorwoo Avatar asked Aug 21 '14 03:08

victorwoo


1 Answers

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

like image 190
Caspar Harmer Avatar answered Sep 24 '22 19:09

Caspar Harmer