0

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

Vynhoû Tawa
  • 68
  • 1
  • 14
  • Two suggestions: make sure the server sends headers not to cache the image (at least not longer than a minute) and add a random number as request parameter after the image URL to bust the browser's cache, e.g. `$scope.urlImage = serverURL + '/Images/background.png?r=' + Math.random();` – Nikos Paraskevopoulos May 24 '16 at 07:57

2 Answers2

2

Try to change url to something like:

var currentTime = new Date().getTime();
$scope.urlImage = serverURL + '/Images/background.png?' + currentTime;
marbug
  • 340
  • 2
  • 10
0

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.. :)

seekers01
  • 560
  • 1
  • 4
  • 11