How to check if file exists from url using angular?

I am working on an Ionic -v1 / Cordova hybrid mobile application and I would like to know how to do this.

So far, I have found an option with the fetch function in the controller function:

angular.module('my.controllers')
.controller('myCtrl', function ($scope, $q, ws){
    var loadImgLst = ws.getImgList().then(function(response){
        //get image src in a list
        var imgList = response;
        var promisesArray = [];
        for(var i in imgList) {
            var promiseSrc = fetch(imgList[i])
                    .then(function(response) {
                var imgurl = response.url; 
                if(!response.ok)
                {
                    //get fallback img
                    imgurl = "http://mysite/img_default.jpg"; 
                }
                return imgurl;
            }).catch(function(error){
                console.log(error);
            });
            promisesArray.push(promiseSrc);
        }
        return $q.all(promisesArray);
    });
    loadImgLst.then(function(lstImg)
    {
        $scope.lstImg = lstImg;
    });
});

In the html view:

<ion-content>
    <div class="list">
        <div ng-repeat="src in lstImg">
            <img ng-src="{{ src }}">
        </div>
    </div>
</ion-content>

When I execute this code in a browser using the ion service, I still have a 404 "Not Found" error in the console, but my default image is displayed.

I tried something similar with the XMLHttpRequest () function and tried / caught, but the result is the same.

Is there a way to avoid (or hide) this error? Another way to solve this problem?

Thank:)

EDIT: I also tried the directive option:

.directive('fallback', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind('error', function() {
                   element.attr('src', attrs.fallback); 
                });
            }
        }
    });

and an html view with a file that does not exist in ng-src:

<img ng-src="http://mysite/no_img.jpg" fallback="http://mysite/img_default.jpg">

I still have this 404 error in the console.

+4
1

HTML :

<img fallback-src="http://mysite/img_default.jpg" ng-src="http://mysite/img.jpg""/>

JS:

myApp.directive('fallback', function () {
  var fallback= {
    link: function postLink(scope, iElement, iAttrs) {
      iElement.bind('error', function() {
        angular.element(this).attr("src", iAttrs.fallback);
      });
    }
   }
   return fallback;
});
0

Source: https://habr.com/ru/post/1687613/


All Articles