Angularjs - 内置指令与NG绑定HTML的不安全 [英] Angularjs - inline directives with ng-bind-html-unsafe

查看:95
本文介绍了Angularjs - 内置指令与NG绑定HTML的不安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是从一段文本的所有主题标签的提取和使用该指令替换它们意味着它应该从这个去:

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>

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

我的想法是使用过滤器来代替该指令HTML这个标签,但我不知道如何,因为表现出来,显然是NG绑定HTML的不安全犯规编译指令。

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.

任何暗示?

推荐答案

创建一个新的指令,其追加到DOM编译后的HTML字符串作为模板:

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);
        }
      );
    };
  }]);
}]);

这篇关于Angularjs - 内置指令与NG绑定HTML的不安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆