Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS. Clear $timeout when invoking angular-ui modal

I have several $timeout expressions in Modal controller

App.controller('ModalCtrl', function ($scope, $timeout) {     for (var i = 0; i < 10; i++) {         (function () {             var timer = $timeout(function () {                 console.log('timer')             }, 1000);         })()     } }) 

I need to clear all the timers when invoking the modal:

App.controller('MainCtrl', function ($scope, $modal, $timeout) {     $scope.showMap = function () {         var modal = $modal.open({             templateUrl: 'modalap.html',             controller: 'modalCtrl',         })          modal.result.then(function () { //fires when modal is resolving         }, function () { //fires when modal is invoking         });     } }) 

How can I do that?

PS Sorry for bad code formatting. I don't know why but I cant format it better. I duplicated code here:

like image 759
user3162402 Avatar asked Jan 09 '14 11:01

user3162402


People also ask

How do you reset a $timeout and disable a watch ()?

var customTimeout = $timeout(function () { // arbitrary code }, 55); $timeout. cancel(customTimeout); The same applies to “$interval()”. To disable a watch, just call it.

What does $Timeout do in AngularJS?

This '$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 the function of the $timeout service?

The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. For repeated calling of a function, see $interval later in this text.

What is timeout in angular?

AngularJS's wrapper for window. 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.


1 Answers

The $timeout service returns a Promise object which can be used to cancel the timeout.

// Start a timeout var promise = $timeout(function() {}, 1000);  // Stop the pending timeout $timeout.cancel(promise); 

To cancel all pending timeouts, you need to maintain a list of promises and cancel the complete list when you open the modal.

like image 186
null Avatar answered Sep 22 '22 15:09

null