Angularjs - 使用ng-bind-html-unsafe的内联指令

时间:2013-08-05 16:38:27

标签: javascript angularjs

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

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

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

我的想法是使用过滤器用指令html替换hashtag,但我不知道如何显示它,因为ng-bind-html-unsafe显然没有编译指令。

任何提示?

1 个答案:

答案 0 :(得分:6)

创建一个新的指令,在将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);
        }
      );
    };
  }]);
}]);