代码如下:
<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>
例如: http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png
是有效的 URL 但 http://www.pacinno.eu/wp- content/uploads/2014/05/placeholder11.png
不是。
此外,随着登录的增加,用户
可能会有很多记录。
最佳答案
您可以使用指令来做到这一点:
这是 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
关于javascript - 如何检查angularjs中是否存在远程图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36148805/