ng-bind-html以防止在内容中执行脚本

时间:2015-06-12 09:03:23

标签: angularjs angularjs-directive angularjs-scope ng-bind-html ng-bind

我面临的问题是我从服务器获取包含HTML内容的数据

<p> hello <a class='mention'data-id='1'>Amerr</a></p>

由于 ng-bind-html Santaize ,它将删除所有潜在威胁以及 data-id =&#39; 1&#39等属性; 即可。我需要哪些指令。所以我用

  1. $ compile 表示我的指令可以作用于锚标记。
  2. $ sce.trustAsHtml返回已编译的代码。
  3. 所以,如果有任何文字,如

    "<p> {{axy}} /p>\n"
    

    $compile(html_code)($scope)

    这将执行代码并导致angular执行表达式导致问题。 帮我解决这个问题。

    &#13;
    &#13;
    var controller= app.controller('Homecontrol', function($scope) {
    
      $scope.body = socket.emit('hello');
      $scope.to_trusted = function(html_code) {
        if (/<[a-z][\s\S]*>/i.test(html_code)) {
          var a = $compile(html_code)($scope);
          return $sce.trustAsHtml(a[0].innerHTML);
        } else {
          return html_code;
        }
      }
    
    });
    
    app.directive('mention', function (){
      return {
        restrict: 'AEC',
        transclude: true,
        template: '<a ng-transclude ></a>',
        replace: true,
       }
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    <p ng-bind-html=toTrust(body) ></p>
    &#13;
    &#13;
    &#13;

1 个答案:

答案 0 :(得分:0)

I finally did by parsing the string by . Jquery.parseHTML and compiled the required DOM with which needs to $compile for directive to act on it. and replaced by the DOM.