I am making a demo in which I am fetching data from the server after regular intervals of time using $interval
Now I need to stop/cancel this.
How I can achieve this? If I need to restart the process, how should I do that?
Secondly, I have one more question: I am fetching data from the server after reqular intervals of time. Is there any need to use $scope.apply
or $scope.watch
?
Here is my plunker:
app.controller('departureContrl',function($scope,test, $interval){
setData();
$interval(setData, 1000*30);
function setData(){
$scope.loading=true;
test.stationDashBoard(function(data){
console.log(data);
$scope.data=data.data;
$scope.loading=false;
//alert(data);
},function(error){
alert('error')
}) ;
}
});
Best Answer
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 createstart()
andstop()
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.