Suppose i have an expression {{name}} , and in the controller i write something like
$timeout(function(){
$scope.name = "Stack Overflow";
},5000);
Then after 5 seconds the expression is evaluated to the string assigned. But if i write the same thing in native setTimeout(), then nothing happens Why? Any behind the scenes weird trick?
setTimeout
: Calls a function or executes a code snippet after a specified delay (MDN).
Angular is not aware of the changes that occur after any code is executed using setTimeout
.
$timeout
is Angular's wrapper for window.setTimeout
. Behind the scenes this wrapper calls the $scope.$apply()
method for you.
You can achieve same behavior if you would call $scope.$apply()
in setTimeout
.
Edit:
// #1
setTimeout(function() {
$scope.name = 'Hola!';
}, 5000);
// #2
setTimeout(function() {
$scope.$apply(function () {
$scope.name = 'Hola!';
});
}, 5000);
// #3
$timeout(function() {
$scope.name = 'Hola!';
}, 5000);
#1 - Angular unaware of update to $scope
#2 - Angular knows that $scope.name has changed
#3 == #2