2

How do I get my model to update automatically after 60 seconds?

I have an array in $scope.tweets that contains a list of tweets. I would like $scope.currentTweet to pop a tweet off the array every 60 seconds.

Is there is a particular way to do this in angular?

Amin Shah Gilani
  • 8,675
  • 5
  • 37
  • 79

2 Answers2

4

Yes you can. AngularJS has $interval for you.

  1. Inject $interval into your controller.
  2. Register it for calling an update function every 60s.

Example:

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);
})
Nam Pham
  • 1,224
  • 13
  • 38
  • 2
    The function passed to `$interval` is automatically wrapped in `$apply`. Calling `$scope.$apply()` from within it will cause a "digest in progress" error. – Igor Raush Oct 28 '15 at 02:24
1

Take a look at the $interval service, which is Angular's wrapper around the native setInterval function.

$interval(function () {
    $scope.currentTweet = $scope.tweets.shift();
}, 60 * 1000);
Igor Raush
  • 15,080
  • 1
  • 34
  • 55