Search code examples
javascripthtmlangularjsbackground-imageng-style

Update background image with same URL periodically


I am working on an angular JS application. My body background must change every minute according to the image hosted by my server.

In my HTML, I use ng-style to set the background image:

<body ng-controller="mainCTRL" ng-style="{backgroundImage: 'url(' + imageURL + ')'}">

In my mainCTRL, imageURL is set like this:

$scope.urlImage = serverURL + '/Images/background.png';

It work well but now I need to refresh the image. The hosted image change every minute but it hosted always on the same URL. To do that, I had this on my JS code:

startRefresh();

function startRefresh() {
    $interval(test, );
}

test = function () {
    $scope.urlImage = '';
    $timeout(function () { 
        $scope.urlImage = serverURL + '/Images/background.png'; 
    }, 1000);
};

The timer works, every minute, the test function is called but the image is always the same.

I would like to have a solution to change the image even if the URL is the same.

--

I'm a javascript beginner and sorry for my english. Thank you


Solution

  • Try to change url to something like:

    var currentTime = new Date().getTime();
    $scope.urlImage = serverURL + '/Images/background.png?' + currentTime;