Skip to content
This repository was archived by the owner on Mar 26, 2019. It is now read-only.
This repository was archived by the owner on Mar 26, 2019. It is now read-only.

Add default image if an error it occurs #8

@Lilipi

Description

@Lilipi

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions