I want to show user image if image exist, like :
<img alt="user_image" src="/images/profile_images/{{result.image}}">
And if user image not available then should show default image , Like
<img alt="user_image" src="/images/default_user.jpg">
How can I do this through angularjs in html page ?
You could create a directive checkImage to check if the image really exist:
<img check-image ng-src="{{img}}" alt="Image" width="100%" >
Directive:
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
});
});
}
};
});
See the demo http://jsfiddle.net/manzapanza/dtt1z5p8/
You can pass in an expression to the alt attribute:
<img alt="{{user_image}}" src="/images/profile_images/{{result.image}}">
Edit: Doh, misread your question. In your controller (or the service which provides the image to the controller), you can set result.image to the user's image or the default image.
Another option is to use conditional logic in ng-src:
<img ng-src="{{ result.image || 'default_user.jpg' }}"/>
This will set the src to result.image if it exists, otherwise to the default.
Personally, I like the first option better since it keeps logic out of the view, but I bet you could find someone who would argue that it belongs in the view since it is view logic.
Edit 2: here is a plnkr: http://plnkr.co/edit/vfYU8T3PlzjQPxAaC5bK?p=preview
The previously mentioned solutions will double the HTTP requests. Every image will be loaded twice!
This solution does not reload the image just to see if it exists:
myApp.directive('checkImage', function() {
return {
link: function(scope, element, attrs) {
element.bind('error', function() {
element.attr('src', '/images/default_user.jpg'); // set default image
});
}
}
});
App.directive('checkImage', function ($q) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
attrs.$observe('ngSrc', function (ngSrc) {
var deferred = $q.defer();
var image = new Image();
image.onerror = function () {
deferred.resolve(false);
element.attr('src', BASE_URL + '/assets/images/default_photo.png'); // set default image
};
image.onload = function () {
deferred.resolve(true);
};
image.src = ngSrc;
return deferred.promise;
});
}
};
});
If you are using Ionic 2 you can try this, it's worked for me:
<img src="{{data.imgPath || 'assets/img/empty.png'}}" >
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With