2014-10-07 55 views
1

我基于此职位的代码AngularJS ngcontroller to be reloading data periodically每3秒重新加载一次数据。单击HTML元素时停止AngularJS自动刷新

我现在的问题是,当我点击某个东西时,我想停止自动刷新。之后,自动刷新将重新开始。

说例如,当我点击按钮停止,自动刷新将停止。当我点击按钮启动它将开始每3秒再次获取数据。

,这里是我的js

var newsfeed = angular.module('newsfeed',[]); 

newsfeed.controller('newsfeedController',function($scope,$http){ 
    var getPosts = function(){ 
     $http.get('http://localhost/must_sns/main/all_status').success(function(data){ 
       $scope.posts = data; 
       console.log(data); 
     }); 
    } 
    getPosts(); 
    setInterval(getPosts, 3000); 
}); 

回答

1

你会使用clearInterval功能:

newsfeed.controller('newsfeedController', function($scope, $http) { 

    var interval; 

    function getPosts() { 
     $http.get('http://localhost/must_sns/main/all_status').success(function(data) { 
      $scope.posts = data; 
      console.log(data); 
     }); 
    } 

    $scope.start = function() { 
     interval = setInterval(getPosts, 3000); 
    }; 

    $scope.stop = function() { 
     clearInterval(interval); 
    }; 

    // Start loading 
    $scope.start(); 

}); 

现在,在HTML中你可以使用start/stop方法:

<button ng-click="start()">Start</button> 
<button ng-click="stop()">Stop</button> 
+0

谢谢。它正在处理按钮(就像我的问题)。但是请注意,在textarea中点击/对焦我的鼠标时是否适用? – 2014-10-07 13:42:03

+0

是的,当然是相同的'ng-click'或'ng-focus'。 – dfsq 2014-10-07 13:43:09

+0

当鼠标失去焦点在textarea后使用'ng-focus'时,我该如何激发'start()'? – 2014-10-07 13:46:35

0

你需要存储返回intervalID。

var myInterval = setInterval(getPosts, 3000); 

那么您可以在其他功能再次停止它(例如,通过按下一个按钮叫,像这样:

clearInterval(myInterval); 

在一个旁注:角用品$interval服务,可能更适合您原因

+0

但我怎么可以申请$间隔?对不起,noob问题 – 2014-10-07 13:34:41

+0

您需要将其注入到您的控制器中,请参阅@sma回答一个示例$ interval – kasoban 2014-10-07 13:35:21

0

使用的setInterval的角度包装:。$interval然后,你可以做这样的事情:

var newsfeed = angular.module('newsfeed',[]); 

newsfeed.controller('newsfeedController',function($scope,$http, $interval){ 
    var getPosts = function(){ 
     $http.get('http://localhost/must_sns/main/all_status').success(function(data){ 
       $scope.posts = data; 
       console.log(data); 
     }); 
    }; 

    getPosts(); 
    var timer = $interval(getPosts, 3000); 

    $scope.stopTimer = function() { 
     $interval.cancel(timer); 
    } 
}); 

您将对定时器的引用存储在变量timer中,然后您可以调用$interval上的cancel函数来停止定时器。

如果您使用Angular wrapper,那么它会使您的代码更具可测试性。您可以使用ngMocks库中的$interval对象来模拟$interval操作。它更好地依赖于Angular wrapper来实现这样的全局函数,以便您的代码更易于测试。