Angular: updating $ scope does not work in setTimeout callback

In angular.js, $scope.greeting = xxx does not work in window.setTimeout . This has no 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?

A full comparison is given below:

+5
source share
3 answers

setTimeout works outside the $digest loop, so angular doesn't know about the change you applied to $scope .

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

See here (your) updated jsfiddle here

+16
source

I think you should use a special service from angular

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope, $timeout) { $scope.greeting = 'init'; $timeout(function(){ $scope.greeting = "hello"; }, 2000); }) 
+4
source

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

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

Source: https://habr.com/ru/post/1200799/


All Articles