Last active
December 18, 2015 02:39
-
-
Save thiagoh/30acc7125ce2a936cb9b to your computer and use it in GitHub Desktop.
Directive to bind safe html in AngularJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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