xeor
xeor

Reputation: 5455

Reloading image in javascript without any parameter-hack

I am trying to display an image and automatically refresh it every minute using AngularJS.

The problem is that the image I am grabbing is from an API that won't allow me to append any bogus stuff to the url to make the url different each time. So, no ?_ts=12356678 and so on...

The current code I have is something like this:

HTML template:

<div data-ng-controller="UpdateController" data-ng-init="image_reloader(timer=2000, url='http://lorempixel.com/400/200/sports/')">
  <img ng-src="{{ image_url }}"></img>
</div>

AngularJS Javascript:

var app = angular.module('app', []);
app.controller('UpdateController', function($scope, $timeout) {
  $scope.image_reloader = function(timer, url) {
    $scope.timer = timer || 10000;
    $scope.updater = function() {
      $scope.image_url = url + '?_ts=' + new Date().getTime();
      $timeout($scope.updater, $scope.timer);
    };
    $scope.updater();
  };
});

This kind of does the trick, except for the ?_ts part which I can't use... Changing the scope.image_url part to $scope.image_url = url; doesn't do anything, it does not try to refresh the image either.

How can I force AngularJS to try to refresh it? I've also tried to set $scope.image_url to '' before changing it to url.

AngularJS is just the framework, any Javascript/jQuery solution would do, but I prefer an AngularJS-related one.

Upvotes: 1

Views: 4899

Answers (2)

xeor
xeor

Reputation: 5455

I sent the vendor of this API a request for adding a dummy parameter so this would be possible, but its been a month now, and no reply.

I've also been thinking about this, and finally found a solution. It is as simple as just using the # sign instead of ?. The hash is never sent to the server, but is still enough for the JavaScript to see it as a different request and hence refetch the image.. Little embarrassed to not have thought about that before now :)

Example (using the workflow I'm doing for this project, not AngularJS optimal

Angular code:

$scope.image_reloader = function(timer, url) {
  $scope.timer = timer || 10000;
  $scope.updater = function() {
    $scope.image_url = url + '#' + new Date().getTime();
    $timeout($scope.updater, $scope.timer);
  };
  $scope.updater();
};

HTML code:

<div ng-controller="UpdateController" ng-init="image_reloader(timer=2000, url='http://lorempixel.com/400/200/sports/')">
  <img ng-src="[[ image_url ]]"></img>
</div>

Upvotes: 3

Hamza Kubba
Hamza Kubba

Reputation: 2269

Something like this should work... note that this isn't tested and you may need to add or subtract 1 from questionMarkIndex.

var questionMarkIndex = $scope.image_url.indexOf("?");
var newurl = (questionMarkIndex  === -1 ? $scope.image_url : $scope.image_url.substring(0, questionMarkIndex); // remove old ts parameter
newurl += '?_ts=' + new Date().getTime();
$scope.image_url += newurl;

Upvotes: -1

Related Questions