60秒后更新角度模型

时间:2015-10-28 02:14:05

标签: javascript angularjs angularjs-scope

如何让我的模型在60秒后自动更新?

我在$scope.tweets中有一个包含推文列表的数组。我希望$scope.currentTweet每60秒从数组中弹出一条推文。

是否有一种特殊方法可以在角度中执行此操作?

2 个答案:

答案 0 :(得分:4)

是的,你可以。 AngularJS有$ interval。

  1. 将$ interval注入您的控制器。
  2. 注册它以每60秒调用一次更新功能。
  3. 示例:

    myApp.controller('MyCtrl', ['$scope', '$interval', function($scope, $interval){
        $scope.tweets = [];
        $scope.currentTweet = null;
        var myUpdater = $interval(function(){
            $scope.currentTweet = $scope.tweets.pop();
        }, 60*1000);
    
        //And you can cancel the interval anytime you want by calling this:
        $interval.cancel(myUpdate);
    })
    

答案 1 :(得分:1)

查看$interval服务,该服务是Angular在原生setInterval函数周围的包装。

$interval(function () {
    $scope.currentTweet = $scope.tweets.shift();
}, 60 * 1000);