1

我的目标是从一段文本中提取所有主题标签并用指令替换它们,这意味着它应该从此开始:

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

进入

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

我的想法是使用过滤器将主题标签替换为指令 html,但我不知道如何显示它,因为 ng-bind-html-unsafe 显然不会编译指令。

有什么提示吗?

4

1 回答 1

6

Create a new directive that compiles the HTML string as a template after appending it to the 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);
        }
      );
    };
  }]);
}]);
于 2013-08-05T17:46:57.897 回答