2014-10-07 40 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來實現這樣的全局函數,以便您的代碼更易於測試。