admin管理员组文章数量:1326677
I was used $interval to run certain function in first controller. After redirect to second controller, still $interval registered function (implemented in first controller) was running. I want to stop $interval services without using destroy function.
I was used $interval to run certain function in first controller. After redirect to second controller, still $interval registered function (implemented in first controller) was running. I want to stop $interval services without using destroy function.
Share Improve this question edited Oct 24, 2016 at 8:59 Pankaj Parkar 136k23 gold badges240 silver badges303 bronze badges asked Feb 4, 2016 at 8:36 jana91jana91 1313 silver badges9 bronze badges2 Answers
Reset to default 5Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.
You could use the cancel
method to clean $interval
object. You should cancel out the interval
while leaving the controller.
For that you need to add eventListener
over $scope
's $destroy
event, you could do cleaning stuff (eg. canceling interval object, canceling timeout object).
Code
var myInterval = $interval(function(){
//your interval code
}, 1000)
//register this listener inside your controller where the interval belongs.
$scope.$on('$destroy', function(){
$interval.cancel(myInterval)
});
Sample Plunkr
Add the interval variable in rootScope. And cancel it in the second controller whenever it gets opened as shown below.
First Controller
$rootScope.stopInterval = $interval(function(){
//code goes here
}, 1000);
Second Controller
$interval.cancel($rootScope.stopInterval);
Note: Only flaw in this case is you need to stop it in all the controllers you use after first controller, but a reliable one.
本文标签: javascriptAngularJs stop interval for specific controllerStack Overflow
版权声明:本文标题:javascript - AngularJs stop $interval for specific controller - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742201511a2432048.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论