简体   繁体   English

AngularJS-带有ng-bind-html-unsafe的内联指令

[英]Angularjs - inline directives with ng-bind-html-unsafe

My aim is to extract from a piece of text all the hashtags and replacing them with a directive this means that it should go from this: 我的目的是从一段文本中提取所有主题标签,并用一条指令替换它们,这意味着它应从此开始:

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

into 进入

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

My idea was to use a filter to replace the hashtag with the directive html, but I have no idea how to show it since, ng-bind-html-unsafe doesnt compile the directive apparently. 我的想法是使用过滤器用指令html替换井号,但是我不知道如何显示它,因为ng-bind-html-unsafe显然不会编译指令。

Any hint? 有什么提示吗?

Create a new directive that compiles the HTML string as a template after appending it to the DOM: 创建一个新指令,将HTML字符串附加到DOM后将其编译为模板:

angular.module('myCompile', [], ['$compileProvider', function($compileProvider) {
  // Allows an attribute's 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);
        }
      );
    };
  }]);
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM