I am using below code, In laravel blade
<div ng-show="displayErrorMsg" class="form-group m-b alert alert-danger">{{errorMsg}}
In angularjs controller
$scope.errorMsg = "Data Empty";
$scope.displayErrorMsg = true;
setTimeout(function() { $scope.displayErrorMsg = false;}, 2000);
Message not disappear after 2 second automatically as given.
But when I simply put alert("test"); or click anywhere message disappears. How to resolve this problem ?
The '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
setTimeout . The fn function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler service. The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed. To cancel a timeout request, call $timeout.
Flushes the queue of pending tasks. This method is essentially an alias of $flushPendingTasks . For historical reasons, this method will also flush non- $timeout pending tasks, such as $q promises and tasks scheduled via $applyAsync and $evalAsync.
Just inject $timeout
in your controller and use this.
$timeout(function() { $scope.displayErrorMsg = false;}, 2000);
Also you can use $digest or $apply as below
setTimeout(function() {
$scope.displayErrorMsg = false;
$scope.$digest();
}, 2000);
setTimeout(function () {
$scope.$apply(function(){
$scope.displayErrorMsg = false;
});
}, 2000);
Check here how these works,
http://www.sitepoint.com/understanding-angulars-apply-digest/
I usually need a function to wait a little bit for any reason, for testing purposes only. In Java, we can use the Thread.sleep(). However, In JavaScript I prefer to use a simple function I found here:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
It has been working for me in several scenarios, including AngularJS. But, please, remember that function shouldn't be used in production environments unless you know exactly what you're doing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With