From e1e74f0dba04e7d5a9ef2ebf700b3558cbdeab2b Mon Sep 17 00:00:00 2001 From: Emilie Date: Thu, 11 Jan 2018 16:00:38 +0100 Subject: [PATCH] Add default image if an error occurs --- index.js | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/index.js b/index.js index e769d73..6bc3a64 100644 --- a/index.js +++ b/index.js @@ -5,9 +5,9 @@ angular.module('angular.img', [ ]).directive('httpSrc', ['$http', function ($http) { return { - // do not share scope with sibling img tags and parent - // (prevent show same images on img tag) - scope: {}, + scope: { + defaultImgSrc: '@' + }, link: function ($scope, elem, attrs) { function revokeObjectURL() { if ($scope.objectURL) { @@ -29,19 +29,23 @@ if(url && url.indexOf('data:') === 0) { $scope.objectURL = url; } else if(url) { - $http.get(url, { - responseType: 'arraybuffer', - headers: { - 'accept': 'image/webp,image/*,*/*;q=0.8' - } - }) - .then(function (response) { - var blob = new Blob( - [ response.data ], - { type: response.headers('Content-Type') } - ); - $scope.objectURL = URL.createObjectURL(blob); - }); + $http.get(url, { responseType: 'arraybuffer' }).then( + function(response) { + if (response.headers('Content-Type').match(/image/g)) { + var blob = new Blob( + [ response.data ], + { type: response.headers('Content-Type') } + ); + $scope.objectURL = URL.createObjectURL(blob); + } else { + $scope.objectURL = $scope.defaultImgSrc; + } + }, + function(data) { + // Handle error here + $scope.objectURL = $scope.defaultImgSrc; + } + ) } }); }