0

I am creating a simple angular directive for reference. When I add it to the HTML page it is working fine but when I add it through HTML tags string and parse with ng-bind-html then it is not working. Please suggest some approach.

Directive:

<notification message="{{message}}"></notification>

//When pass through controller object, It's not working
$scope.htmlContent = '<p>Hello</p><notification message="{{message}}"></notification>';

Plunker

rakemen
  • 346
  • 4
  • 14
Satnam Singh
  • 63
  • 1
  • 13

1 Answers1

0

You need to call a compile directive to achieve this functionality

JS Code

var app = angular.module('plunker', ['ngRoute', 'ui.bootstrap',]);

app.filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]);

    app.controller("MessageCtrl", function($scope) {
    $scope.message = "Product created!";
     $scope.htmlContent = '<notification message="{{message}}"></notification>';

})
app.directive("notification", function() {
    return {
        restrict: 'E',
        scope: {
            message: '@'
        },
        template: '<div class="alert">{{message}}</div>'
    }
});

app.directive('compile', ['$compile', function ($compile) {
      return function(scope, element, attrs) {
          scope.$watch(
            function(scope) {
               // watch the 'compile' expression for changes
              return scope.$eval(attrs.compile);
            },
            function(value) {
              // when the 'compile' expression changes
              // assign it into the current DOM
              element.html(value);

              // compile the new DOM and link it to the current
              // scope.
              // NOTE: we only compile .childNodes so that
              // we don't get into infinite loop compiling ourselves
              $compile(element.contents())(scope);
            }
        );
    };
}]);

HTML code

<div ng-controller="MessageCtrl">
   <div compile="htmlContent"></div>
   <notification message="{{message}}"></notification>
</div>

Check Plunker

You can read more about this in this answer

Community
  • 1
  • 1
nishant agrawal
  • 471
  • 2
  • 7