angular-img-http-src icon indicating copy to clipboard operation
angular-img-http-src copied to clipboard

Add default image if an error it occurs

Open Lilipi opened this issue 7 years ago • 0 comments

Hello there, I've modified your code to complete it if an error it occurs.

`(function () { 'use strict'; /*global angular, Blob, URL */

angular.module('angular.img', [
]).directive('httpSrc', ['$http', function ($http) {
	return {
        scope: {
            defaultImgSrc: '@'
        },
		link: function ($scope, elem, attrs) {
			function revokeObjectURL() {
				if ($scope.objectURL) {
					URL.revokeObjectURL($scope.objectURL);
				}
			}

			$scope.$watch('objectURL', function (objectURL) {
				elem.attr('src', objectURL);
			});

			$scope.$on('$destroy', function () {
				revokeObjectURL();
			});

			attrs.$observe('httpSrc', function (url) {
				revokeObjectURL();

				if(url && url.indexOf('data:') === 0) {
					$scope.objectURL = url;
				} else if(url) {
					$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;
						}
					)
				}
			});
		}
	};
}]);

}()); `

Like this, if an error it occurs during http get or if the result isn't an image, a default image is used.

For this, you have to add the following attribute : default-img-src on img tag. Example :

<img http-src='{{attachedTo}}' default-img-src="{{vm.defaultPreview}}"/>

Feel free to use it if you want.

Lilipi avatar Jan 09 '18 14:01 Lilipi