Skip to content

Instantly share code, notes, and snippets.

@slucero
Created September 9, 2014 20:57
Show Gist options
  • Save slucero/dbadd483ac09fe1bbe9d to your computer and use it in GitHub Desktop.
Save slucero/dbadd483ac09fe1bbe9d to your computer and use it in GitHub Desktop.
Angular Compile Content Directive
/**
* Directive for compiling HTML loaded on-the-fly.
*
* Compiles the assigned scope attribute and inserts it inside the current element.
*
* Usage: Assign scope value name containing content to be compiled and inserted
* to compile-content attribute.
*
* Example: <div compile-content="htmlContent"></div>
* This assumes that $scope.htmlContent contains a sanitized HTML string.
*/
coreModule.directive('compileContent', ['$parse', '$compile', function($parse, $compile) {
return {
restrict: 'A',
link: function(scope, element, attr) {
// Set up defined scope attribute for parsing and watching for changes
var parsed = $parse(attr.compileContent);
function getStringValue() { return (parsed(scope) || '').toString(); }
// Watch for changes in designated scope value
scope.$watch(getStringValue, function(newVal) {
if (newVal) {
// Replace element content with parsed values
element.html(newVal);
// Compile element content
$compile(element.contents())(scope);
}
});
},
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment