0

I'm new to angular...

$scope.imageUrl[0] = 'images/' + $scope.repos[i].name + '.png';
$scope.imageUrl[1] = 'images/placeholder.png';

$scope.repos[i].imgSrc = (Utils.isImage($scope.imageUrl[0])) ? $scope.imageUrl[0] : $scope.imageUrl[1];

Utils.isImage() is from the following factory:

app.factory('Utils', function($q) {
return {
  isImage: function(src) {

    var deferred = $q.defer();

    var image = new Image();
    image.onerror = function() {
      deferred.resolve(false);
      return false;
    };
    image.onload = function() {
      deferred.resolve(true);
      return true;
    };

    image.src = src;

    return deferred.promise;
   }
 };
});

The image url is generated from an api response object. I'm using Utils.isImage() to check if the generated image url exists in the images folder on the server. But the (Utils.isImage($scope.imageUrl[0])) is still true even if the image is found on the server or not found. How can I fix this?

Plunker link - portfolio

1
  • what is that Utils? I would make this on server side - server should know what images it has. Dec 25, 2014 at 18:35

2 Answers 2

0

The Utils.isImage function return a promise so is always true.

Angular use the $qservice to provide asynchronous functionality. (documentation)

To correctly handle the promise you should use at least the then() function and provide callbacks for a resolved or rejected promise.

Utils.isImage($scope.imageUrl[0])).then(
   function() {
      // Here is true  
      $scope.repos[i].imgSrc = $scope.imageUrl[0]
   },
   function() {
      // Here is false
      $scope.repos[i].imgSrc = $scope.imageUrl[1]
   }
)
2
0

Well you can simply write a directive something like this:

myAppModule.directive('noImageIcon', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            var defaultURL = attr.defaultURL || 'images/plaecholder.png';

            attr.$observe('ngSrc', function(newValue) {
                if (!newValue) {
                    element.attr('src', defaultURL);
                } else {
                    var image = new Image();
                    image.onerror = function() {
                         element.attr('src', defaultURL);
                    };
                    image.onload = function() {
                    };

                    image.src = newValue;
                }
            });
        }
    };
});

Now your image html tag will be like:

<img ng-repeat="repo in repos" ng-src="images/{{repo.name}}.png" />
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.