Skip to content

Instantly share code, notes, and snippets.

@flammenmensch
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save flammenmensch/2a3dbd6c426f8d59bef8 to your computer and use it in GitHub Desktop.

Select an option

Save flammenmensch/2a3dbd6c426f8d59bef8 to your computer and use it in GitHub Desktop.
Angular.js CSP module
angular.module('csp', [ ])
.factory('imageLoader', [ '$http', function ($http) {
return {
load: function (url) {
return $http.get(url, {
cache: true,
responseType: 'blob'
}).then(function (response) {
return URL.createObjectURL(response.data);
});
},
unload: function (blob) {
blob && URL.revokeObjectURL(blob);
}
};
} ])
.directive('cspSrc', [ 'imageLoader', function (imageLoader) {
return {
restrict: 'A',
priority: 99,
scope: {
cspSrc: '@cspSrc'
},
link: function (scope, element, attributes) {
scope.$watch('cspSrc', function (newValue) {
if (newValue !== undefined) {
imageLoader.load(newValue).then(function (blob) {
attributes.$set('src', blob);
});
}
});
scope.$on('$destroy', function () {
imageLoader.unload(attributes['src']);
});
}
};
} ]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment