Tuz
Tuz

Reputation: 1980

Detect 404 image status on angularjs when click on a button

I have the following button directive :

 <button-data></button-data>

the button data directive template is:

<div class="buttonDiv">
<a ng-show="!isSomthing" class="{{className}}" >
</a>
</div>

in another place , I have a canvas (some plugin) that show an image

When clicking on the button I would like to check if the image response is 404 or other broken status and disable the button in that case(event just return in the "link" directive function without doing anything)

Hos could I do that?

thanks

Upvotes: 1

Views: 46

Answers (1)

lin
lin

Reputation: 18392

Try to get it before you display it. A simple $http get request is what you are looking for:

View

<div ng-controller="MyCtrl">
  <button load-image image-src="imageSource">check photo</button>
  <button load-image image-src="imageSourceInvalide">check photo</button>
</div>

AngularJS application

var myApp = angular.module('myApp', []);

myApp.controller("MyCtrl", function($scope) {
  $scope.imageSource = 'https://i.imgur.com/hlF1AEug.jpg';
  $scope.imageSourceInvalide = 'https://i.imgur.com/nonono';
});


myApp.directive('loadImage', function($http) {
  return {
    restrict: 'A',
    scope: {
      imageSrc: '='
    },
    link: function(scope, element) {
      element.on('click', function() {
        $http.get(scope.imageSrc).then(function(data) {

          element.append('<img src="' + scope.imageSrc + '">');

        }, function errorCallback(response) {
          console.log('could not load image');
        })
      });
    }
  }
});

> demo fiddle

Upvotes: 1

Related Questions