Skip to content

Instantly share code, notes, and snippets.

@thiagoh
Last active December 18, 2015 02:39
Show Gist options
  • Save thiagoh/30acc7125ce2a936cb9b to your computer and use it in GitHub Desktop.
Save thiagoh/30acc7125ce2a936cb9b to your computer and use it in GitHub Desktop.
Directive to bind safe html in AngularJS
// bind safe html in AngularJS
angular.module('myModule', ['ngSanitize'])
.directive('tgBindSafeHtml', ['$sce', '$sceDelegate', '$parse', '$compile',
function($log, $sce, $sceDelegate, $parse, $compile) {
return {
restrict: 'A',
compile: function ngBindHtmlCompile(tElement, tAttrs) {
var ngBindHtmlGetter = $parse(tAttrs.tgBindSafeHtml);
var ngBindHtmlWatch = $parse(tAttrs.tgBindSafeHtml, function getStringValue(value) {
return (value || '').toString();
});
return function ngBindHtmlLink(scope, iElement, attr) {
scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
// we re-evaluate the expr because we want a TrustedValueHolderType for $sce, not a string
iElement.html($sceDelegate.valueOf($sce.trustAsHtml(ngBindHtmlGetter(scope))) || '');
});
};
}
};
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment