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

标签 javascript angularjs

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

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

进入

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

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

有什么提示吗?

最佳答案

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

关于javascript - Angularjs - 带有 ng-bind-html-unsafe 的内联指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18063280/

相关文章:

javascript - 尝试将 jquery $.when() & .done() 与 2x $.ajax 调用一起使用,但 did() 立即被调用

angularjs - ngSanitize 模块注入(inject)错误

javascript - Angular Js - 避免在 ng-repeat 中重复

javascript - Angular $scope.$apply 无法与 form.submit() 一起正常工作

javascript - 从单个服务调用返回多个“独立”异步结果的正确 Angular 模式是什么

javascript - 如何检索 Ember.js 模型的所有属性

javascript - ionic 启动画面卡住

javascript - ng 类访问元素文本

Javascript 对象/函数在另一个对象/函数中的可访问性

JavaScript:对 ASCII 字符串和非 ASCII 字符串的混合数组进行排序