You can store the promise returned by the interval and use $interval.cancel()
to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start()
and stop()
functions whenever you want to stop and start them again from a specific event. I have created a snippet below showing the basics of starting and stopping an interval, by implementing it in view through the use of events (e.g. ng-click
) and in the controller.
angular.module('app', [])_x000D_
_x000D_
.controller('ItemController', function($scope, $interval) {_x000D_
_x000D_
// store the interval promise in this variable_x000D_
var promise;_x000D_
_x000D_
// simulated items array_x000D_
$scope.items = [];_x000D_
_x000D_
// starts the interval_x000D_
$scope.start = function() {_x000D_
// stops any running interval to avoid two intervals running at the same time_x000D_
$scope.stop(); _x000D_
_x000D_
// store the interval promise_x000D_
promise = $interval(setRandomizedCollection, 1000);_x000D_
};_x000D_
_x000D_
// stops the interval_x000D_
$scope.stop = function() {_x000D_
$interval.cancel(promise);_x000D_
};_x000D_
_x000D_
// starting the interval by default_x000D_
$scope.start();_x000D_
_x000D_
// stops the interval when the scope is destroyed,_x000D_
// this usually happens when a route is changed and _x000D_
// the ItemsController $scope gets destroyed. The_x000D_
// destruction of the ItemsController scope does not_x000D_
// guarantee the stopping of any intervals, you must_x000D_
// be responsible for stopping it when the scope is_x000D_
// is destroyed._x000D_
$scope.$on('$destroy', function() {_x000D_
$scope.stop();_x000D_
});_x000D_
_x000D_
function setRandomizedCollection() {_x000D_
// items to randomize 1 - 11_x000D_
var randomItems = parseInt(Math.random() * 10 + 1); _x000D_
_x000D_
// empties the items array_x000D_
$scope.items.length = 0; _x000D_
_x000D_
// loop through random N times_x000D_
while(randomItems--) {_x000D_
_x000D_
// push random number from 1 - 10000 to $scope.items_x000D_
$scope.items.push(parseInt(Math.random() * 10000 + 1)); _x000D_
}_x000D_
}_x000D_
_x000D_
});
_x000D_
<div ng-app="app" ng-controller="ItemController">_x000D_
_x000D_
<!-- Event trigger to start the interval -->_x000D_
<button type="button" ng-click="start()">Start Interval</button>_x000D_
_x000D_
<!-- Event trigger to stop the interval -->_x000D_
<button type="button" ng-click="stop()">Stop Interval</button>_x000D_
_x000D_
<!-- display all the random items -->_x000D_
<ul>_x000D_
<li ng-repeat="item in items track by $index" ng-bind="item"></li>_x000D_
</ul>_x000D_
<!-- end of display -->_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_