Holy Crap Holy Crap - 18 days ago 6
AngularJS Question

How to make an AngularJS directive to change the src attribute of an image?

I want to create a angular directive for my image tags that changes the image src to a random image in a collection or through a call to a service. The change should should happen after 5 seconds or as an input to the directive. Is this possible and could someone help me starting?

I will also add animations to this but, thats for later.....

As a newbie to AngularJS any help or directions would be appreciated.

Thanks.

Answer

When one writes an img tag source like this:

<img ng-src='{{imagesrc}}' />

The image source attribute gets bound to the variable imagesrc, which you can then change in JS, such as by using $timeout:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $timeout) {
  $scope.name = 'World';
  $scope.imagesrc = "http://www.steff.qc.ca/main/wp-content/uploads/2010/03/phoenix.gif";
  $timeout(function() {
    $scope.imagesrc = "http://im2-tub-ru.yandex.net/i?id=3fb6126a9a8ea667700f698b774e34d3-90-144&n=21";
  }, 1000);
});

See full plunkr here: http://plnkr.co/edit/q7dI6N6skuGlhfQTqyQT?p=preview