Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply delay on AngularJS

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 ?

like image 539
Rita Avatar asked Feb 22 '16 07:02

Rita


People also ask

What does $Timeout do in angular?

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.

What is setTimeout in angular?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

How does $Timeout work in AngularJS?

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.

What does timeout flush do?

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.


2 Answers

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/

like image 185
GRESPL Nagpur Avatar answered Nov 07 '22 08:11

GRESPL Nagpur


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.

like image 8
Almir Campos Avatar answered Nov 07 '22 06:11

Almir Campos