以下是代码:
<div ng-repeat="u in users">
<!--I will always receive a URL -->
<div ng-if="u.imageUrl"> <!--Here I want to check if the provided URL is active-->
<!--Only seen if image url is live and active -->
</div>
<div>
<!--do some other things-->
</div>
</div>
e.g。 :http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png
是有效网址,但http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder11.png
不是。
随着登录的增加,users
也可能有许多记录。
答案 0 :(得分:1)
您可以使用指令执行此操作:
以下是JSFiddle
JS:
.directive('userAvatar', function() {
return {
link: function(scope, element, attrs) {
var placeholder = 'path/to/your/placeholder.jpg';
scope.$watch(function() {
return attrs.ngSrc;
}, function (value) {
if (!value) {
element.attr('src', placeholder);
}
});
element.bind('error', function() {
element.attr('src', placeholder);
});
}
};
});
HTML:
<div ng-repeat="u in users">
<div>
<img ng-src="{{u.imageUrl}}" user-avatar />
</div>
<div>
现在,如果ng-src
值是404未找到的图片,则会将其替换为默认placeholder