Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 997
Graham Avatar asked Dec 24 '22 02:12

Graham


2 Answers

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.

like image 158
illeb Avatar answered Jan 02 '23 22:01

illeb


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);
}
like image 42
Paul Fitzgerald Avatar answered Jan 02 '23 22:01

Paul Fitzgerald