admin管理员组文章数量:1429735
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.
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.
Share Improve this question asked Jan 26, 2015 at 16:28 TheVikingTheViking 1713 silver badges15 bronze badges2 Answers
Reset to default 6When 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/i?id=3fb6126a9a8ea667700f698b774e34d3-90-144&n=21";
}, 1000);
});
See full plunkr here: http://plnkr.co/edit/q7dI6N6skuGlhfQTqyQT?p=preview
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.
本文标签: javascriptHow to make an AngularJS directive to change the src attribute of an imageStack Overflow
版权声明:本文标题:javascript - How to make an AngularJS directive to change the src attribute of an image? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745552680a2663015.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论