Angular documentation约$ interval正在说:
Note: Intervals created by this service must be explicitly destroyed when you are finished with them.
但它不解释如何销毁$ interval。
如果例如我有一个包含这个代码的指令:
- $interval(function() {
- for (var i in myArray) {
- // do domething
- }
- },5000);
每当用户更改页面时,与路由控制器(在下面的示例中为/ page1)相关联的范围将被发送
a
$destroy
event.您可以在侦听器中取消该事件的$ interval:
- app.config(function ($routeProvider) {
- $routeProvider.when('/page1',{
- template: '<div>Page Content</div>',controller: PageController
- });
- // ...
- });
- function PageController($scope,$interval) {
- var intervalPromise = $interval(function () { /* ... */ },5000);
- $scope.$on('$destroy',function () { $interval.cancel(intervalPromise); });
- }