Vynhoû Tawa
Vynhoû Tawa

Reputation: 68

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

Upvotes: 0

Views: 507

Answers (2)

marbug
marbug

Reputation: 350

Try to change url to something like:

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

Upvotes: 2

seekers01
seekers01

Reputation: 560

Try this change in your test function:

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

Hope this works for you.. :)

Upvotes: 0

Related Questions