Graham Graham - 3 months ago 9
AngularJS Question

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?

Answer

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.

Comments