Escape HTML text in an AngularJS directive

后端 未结 9 901
执念已碎
执念已碎 2020-12-05 07:12

Is there an angular JS command that will do HTML escaping on text? I am processing a custom directive and have need to escape some of the output which it generates.

9条回答
  •  囚心锁ツ
    2020-12-05 07:44

    There are two ways to do HTML sanitization in AngularJS. The first is by using the ngBindHtml directive and the second by using the $sanitize service.

    function MyCtrl ( $scope, $sanitize ) {
      $scope.rawHtml = "
    "; $scope.sanitizedHmtl = $sanitize( $scope.rawHtml ); }

    Then these two are functionally equivalent:

    If used in a directive, as in your question, you can simply insert the sanitized HTML:

    element.html( scope.sanitizedHtml );
    

    But in most cases when writing directives, you'd have this in a template and use ngBindHtml, as above. But it works for the corner cases.

提交回复
热议问题