1

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.

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your time and effort. But this is to basic even for me :-) Im looking for an example how this could be done in a directive because I want to create a carousel-like thing. Lets say images placed in three rows and three columns of a table. That is nine images. Each an one of them should be changed at random times with new randomly selected images from an array of images. Do I get myself clear here?
Wow!! Thanks Petr!!!! Looks like you have hit the nail. I'll take a closer look at this tonight.
-1

You can write a directive, and in the link function write something like this:

function link(scope, element, attrs) {
    var format,
        timeoutVal;

    function updateAttrs(value) {
      element.attr('src', value));
    }

    element.on('click', function() {
      updateAttrs(value);
    });
  }

Somwhere in the link you can use angular $timeout. This code snippet does not work but it could give you some some idea of the mechanism. Another way is to use ng-mouseover and create in the parent controller a function, which will change attrs of the element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.