简体   繁体   中英

How to check remote image exists in angularjs?

Below is the code :

<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>

eg : http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png is active URL but http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder11.png is not. Also users may have many records as signin increases.

You can do that with a directive:

Here is the 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>

So now if the ng-src value is a 404 not found image it will be replaced with the default placeholder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM