4

I don't think this is directly an issue but I don't know how to do this. I'm trying to dynamically load content that uses UI Bootstrap directives but when the content is loaded UI Bootsrap components don't work. Being more specific, tooltips don't work. Here is the important code:

<div ng-bind-html="trustSnippet(f.field.contentAfter)"></div>

The javascript

$scope.trustSnippet = function(snippet) {
          return $sce.trustAsHtml(snippet);
};

The HTML I'm trying to inject is:

<i class="fa fa-exclamation-circle" tooltip-placement="right" tooltip="On the Right!"></i>

Any clues?

TY

1
  • Provide minimal, runnable example. As it stands this is unanswerable. Commented Feb 11, 2015 at 22:07

2 Answers 2

3

This is because ng-bind-html doesn't compile the inserted elements, and so the UI Bootstrap directives - or any other directive or expression, for that matter, would not work.

If you are getting the HTML from a particular location, you could simply use ng-include.

For static location:

<div ng-include="'path/to/html'"></div>

Or, if the location is dynamic and stored in a scope-exposed variable: $scope.path = "path/to/html";:

<div ng-include="path"></div>

Otherwise, if the HTML itself with Angular expressions/directives is dynamically generated or imported (a rare case, which should make you re-examine your design to make sure that you are not offending any best practices), you would need to compile it using $compile service, and it is better done using a directive:

app.directive("ngBindHtmlCompile", function($compile, $sce){
  return {
    restrict: "A",
    link: function(scope, element, attrs){
      scope.$watch($sce.parseAsHtml(attrs.ngBindHtmlCompile), function(html){
        var el = angular.element("<div>").html(html);
        element.empty();
        element.append(el.children());
        $compile(element.contents())(scope);
      })
    }
  };
});

Don't forget to add "ngSanitize" as a dependency. The usage is:

<div ng-bind-html-compile="html"></div>
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thank you for your answer. I had to resolve my issue a week a go and got to the same answer you provided. I had to compile the html each time. Anyway thank for your explanation, now I get a deeper understanding.
1

I was facing the same problem. The following method worked for me.

In HTML,

<div ng-bind-html="f.field.contentAfter | unsafe"></div>

In Javascript,

app.filter('unsafe', function($sce) {
  return function(val) {
      return $sce.trustAsHtml(val);
  }; 
});

1 Comment

The answer of @dsaket should be the accepted answer as this is much cleaner. The return though works even without adding the "val". app.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.