Angular with $ sce and $ compile

I am creating a template builder that ultimately saves the html of a specific div in a database with a bunch of inline styles and ng-click links.

I am trying to display the saved html in the main div container using a custom directive, but I am having problems with $ sce and $ compile, which play well together.

This is my tpl directive

angular.module('hub').directive('tpl', ['$compile', '$parse', '$sce', function ($compile, $parse, $sce) {
  return {
    restrict: 'A',
    replace: true,
    link: function(scope, elem, attrs) {
      scope.$watch(attrs.tpl, function (html) {
        var parse = $sce.parseAsHtml(attrs.tpl);
        console.log(parse);//this is  function, but calling it returns undefined

        //this does not work! Just renders a blank container, no error in console
        //elem.html(parse);
        //this works, but throws an $sce error as unsafe
        elem.html($parse(attrs.tpl)(scope));
        $compile(elem.contents())(scope);
      });
    }
  }
}]);

And the HTML that calls the directive

<div id="builder-stage">
  <div id="template-container"  tpl="formData.template.markupWide">
    <div class="template-inner" style="height: 776px;"></div>
  </div>
</div>

I can get this to work by ignoring the $ sce error, but it makes me uneasy, although I render the saved html on the server side harmless.

Can someone explain to me how I can make this $ sce.parseAsHtml action work?

+4
source share

All Articles