StackOverflow_23147757: canceling-an-angular-interval-and-its-promise
Illustration of answer to http://stackoverflow.com/questions/23147757/canceling-an-angular-interval-and-its-promise.
by ExpertSystem
HTML
<script src="http://code.angularjs.org/1.2.16/angular.min.js"></script>
<div ng-controller="myCtrl">
<button ng-click="startTimer()">Start timer</button>
<button ng-click="stopTimer()">Cancel timer</button>
<div>Interval cancelled: {{!!timer.cancelled}}</div>
<div>{{someText}}</div>
</div>
JavaScript
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($interval, $scope) {
var intervalDelay = 1000;
var intervalFunc = function () {
$scope.someText += '.';
}
$scope.timer;
$scope.startTimer = function () {
if ($scope.timer) {
$interval.cancel($scope.timer);
}
$scope.someText = 'Processing';
$scope.timer = $interval(intervalFunc, intervalDelay);
};
$scope.stopTimer = function () {
if ($scope.timer) {
$interval.cancel($scope.timer);
}
};
});
app.config(function ($provide) {
$provide.decorator('$interval', function ($delegate) {
var originalCancel = $delegate.cancel.bind($delegate);
$delegate.cancel = function (intervalPromise) {
var retValue = originalCancel(intervalPromise);
if (retValue && intervalPromise) {
intervalPromise.cancelled = true;
}
return retValue;
};
return $delegate;
});
});