mhanisch mhanisch - 1 year ago 86
AngularJS Question

AngularJS directive in ng-bind-html

In the application I am working on, a service supplies the app with a json, containing HTML. I output the HTML in a template like this:

<div ng-bind-html="renderHtml(widget.article.body)"></div>

This HTML may contain custom directives, like an inline-chart:

directiveModule.directive('inlineChart', function(){
return {
restrict: 'A',
scope: { inline-widget:'=elem' },
template: '<p ng-bind="inline-widget.blah"></p>'

If I use the directive normally in a template, everything works fine, but it seems it is not being touched when used in ng-bing-html with the renderHtml function.

Any suggestions how this could be realised are very much appreciated!

Answer Source

You need to import the ngSanitize module and use the $sce service. It should look something like this:

// Remember the following comes from angular-sanitize.js found on the angular website and
// also must be included in the web app.
angular.module('myApp', ['ngSanitize']);
  .controller('MyCtrl', function($scope, $sce) {
    //... other controller code
    $scope.renderHtml = function(html) {
      return $sce.trustAsHtml(html);

In short, the $sce service will mark the html as trusted. You can find documentation here

EDIT: I realize I may have not answered the question. It seems that you're asking about binding scope variables to the directive that is rendered within your directive? In order to get elements to compile properly, you're going to have to use the $compile service and change your logic up a bit. First, the template:

<p class="place-directive-here"></p>

Then the directive:

  .directive('myDirective', function($compile) {
    return {
      scope: {
        inlineWidget: '='
      template: '<p class="place-directive-here"></p>',
      link: function(scope, elem, attrs) {
        var placement = elem.find('.place-directive-here');
        scope.$watch('inlineWidget', function(widget){
          // Compile the html against the scope. This will bind the dom to your
          // current scope
          var newElement = $compile(widget.blah)(scope);
          // Place in the view

You can find the compile documentation here. Hopefully this is a more comprehensive answer to what you're looking for.

EDIT 2: For clarification, the directive should look like this on the page:

<div my-directive inline-widget="someInlineWidget"></div>

The place-directive-here class is just a handle for the directive to find your <p> tag and render inside of it. However, if angular is not concerned with the html that is rendered inside of my-directive, the first solution that I provided should work just fine and the template property of my-directive should be:

template: '<p ng-bind-html="renderHtml(inlineWidget.blah)"></p>'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download