Angularjs - inline directives with ng-bind-html-unsafe

My goal is to extract all the hashtags from a piece of text and replace them with a directive, which means it should go from this:

<p>Hello #stackoverflow this is a #test<p>

      

in

<p>Hello <hashtag="stackoverflow"></hashtag> this is a #test<p>

      

My idea was to use a filter to replace hashtags with the html directive, but I have no idea how to show this as ng-bind-html-unsafe does not compile the directive apparently.

Any hints?

+1


source to share


1 answer


Create a new directive that compiles the HTML string as a template after adding it to the DOM:



angular.module('myCompile', [], ['$compileProvider', function($compileProvider) {
  // Allows an attribute value to be evaluated and compiled against the scope, resulting
  // in an angularized template being injected in its place.
  //
  // Note: This directive is suffixed with "unsafe" because it does not sanitize the HTML. It is up
  // to the developer to ensure that the HTML is safe to insert into the DOM.
  //
  // Usage:
  //     HTML: <div my-compile-unsafe="templateHtml"></div>
  //     JS: $scope.templateHtml = '<a ng-onclick="doSomething()">Click me!</a>';
  //     Result: DIV will contain an anchor that will call $scope.doSomething() when clicked.
  $compileProvider.directive('myCompileUnsafe', ['$compile', function($compile) {
    return function(scope, element, attrs) {
      scope.$watch(
        function(scope) {
          // watch the 'compile' expression for changes
          return scope.$eval(attrs.myCompileUnsafe);
        },
        function(value) {
          // when the 'compile' expression changes
          // assign it into the current DOM element
          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);
        }
      );
    };
  }]);
}]);

      

+6


source







All Articles