Graham
Graham

Reputation: 1517

Call a function periodically in angular

I have an angular controller which displays a backgroud image and text message. The controller is:

var myArchiveController = function($scope) {

     var setBackground = function() {
         $scope.backgroundUrl = someUrlFromService;
         $scope.backgroundMessage = someMessageFromService;
     }

     setBackground();
}

app.controller("myController", myController);

How can I call the setBackground() function periodically, e.g. every minute?

Upvotes: 4

Views: 2674

Answers (2)

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

The following should do it for you.

setInterval(setBackground, 60000);

or else, and the preferred approach, is to use angular's $interval service - $interval(setBackground, 60000);

You will need to inject the interval service ($interval) into the controller and then the code will be as follows:

var myArchiveController = function($scope, $interval) {

   //code here

    $interval(setBackground, 60000);
}

Upvotes: 2

illeb
illeb

Reputation: 2947

Use angular $interval service:

var myArchiveController = function($scope, $interval) {

    var setBackground = function() {
        $scope.backgroundUrl = someUrlFromService;
        $scope.backgroundMessage = someMessageFromService;
    }

    $scope.intervalIstance = $interval(setBackground, 60000);
} 

To stop it Arbitrarily, use $interval.cancel.

$interval.cancel($scope.intervalIstance);

Don't forget to include $interval it in your dependencies.

Upvotes: 8

Related Questions