如果图像存在,我想显示用户图像,例如:
<img alt="user_image" src="/images/profile_images/{{result.image}}">
如果用户图像不可用,则应显示默认图像,例如
<img alt="user_image" src="/images/default_user.jpg">
如何通过 html 页面中的 angularjs 来做到这一点?
最佳答案
您可以创建一个指令 checkImage 来检查图像是否确实存在:
<img check-image ng-src="{{img}}" alt="Image" width="100%" >
指令:
myApp.directive('checkImage', function($http) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
attrs.$observe('ngSrc', function(ngSrc) {
$http.get(ngSrc).success(function(){
alert('image exist');
}).error(function(){
alert('image not exist');
element.attr('src', '/images/default_user.jpg'); // set default image
});
});
}
};
});
关于如果原始图像不存在,AngularJS显示默认图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28345682/