Last active
March 24, 2018 08:11
-
-
Save dassiorleando/670b98a2e3b422e8692e304cacfa0443 to your computer and use it in GitHub Desktop.
Using $timeout and setTimout in AngularJs App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Simple script to show how to solve the scrope update | |
* When using the native js TimeOut call | |
* | |
* @author dassiorleando | |
*/ | |
(function (angular) { | |
'use strict'; | |
angular | |
.module('myApp', []) // Define our angular app | |
.controller('IndexController', IndexController); // We setup the controller | |
IndexController.$inject = ['$scope', '$timeout']; | |
function IndexController($scope, $timeout) { | |
$scope.firstMessage = 'First message'; | |
$scope.secondMessage = 'Second message'; | |
// Let's update the first message after 2 seconds | |
// Angular $timeout service | |
$timeout(function() { | |
$scope.firstMessage = 'First message updated'; | |
alert($scope.firstMessage); | |
}, 2000); | |
// Let's update the second message after 2 seconds | |
// Native implementation | |
setTimeout(function() { | |
$scope.secondMessage = 'Second message updated'; | |
alert($scope.secondMessage); | |
}, 2000); | |
// Be aware that if the $timeout was called at the second place the digest could be also updated | |
// That means both messages will be updated despite the use of setTimeout. | |
} | |
})(window.angular); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for sharing