从AngularJS控制器将HTML插入视图

时间:2012-02-21 17:12:12

标签: javascript angularjs escaping html-sanitizing

是否可以在AngularJS控制器中创建HTML片段并在视图中显示此HTML?

这要求将不一致的JSON blob转换为id : value对的嵌套列表。因此,HTML是在控制器中创建的,我现在希望显示它。

我创建了一个模型属性,但是如果不打印HTML,则无法在视图中呈现它。


更新

问题似乎是由于角色将创建的HTML呈现为引号内的字符串而产生的。将试图找到解决方法。

控制器示例:

var SomeController = function () {

    this.customHtml = '<ul><li>render me please</li></ul>';
}

示例视图:

<div ng:bind="customHtml"></div>

给予:

<div>
    "<ul><li>render me please</li></ul>"
</div>

19 个答案:

答案 0 :(得分:1093)

对于Angular 1.x,请在HTML中使用ng-bind-html

<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>

此时您会收到attempting to use an unsafe value in a safe context错误,因此您需要使用ngSanitize$sce来解决此问题。

$ SCE

在控制器中使用$sce.trustAsHtml()转换html字符串。

 $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);

ngSanitize

有两个步骤:

  1. 包括angular-sanitize.min.js资源,即: <script src="lib/angular/angular-sanitize.min.js"></script>

  2. 在js文件(控制器或通常是app.js)中,包含ngSanitize,即:
    angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])

答案 1 :(得分:307)

你也可以像这样创建一个过滤器:

var app = angular.module("demoApp", ['ngResource']);

app.filter("trust", ['$sce', function($sce) {
  return function(htmlCode){
    return $sce.trustAsHtml(htmlCode);
  }
}]);

然后在视图中

<div ng-bind-html="trusted_html_variable | trust"></div>

注意:此过滤器信任传递给它的所有html,如果传递了带有用户输入的变量,则可能会出现XSS漏洞。

答案 2 :(得分:116)

Angular JS shows HTML within the tag

上面链接中提供的解决方案对我有用,此线程中没有任何选项。对于任何使用AngularJS版本1.2.9寻找相同内容的人

这是一份副本:

  

好的,我找到了解决方法:

     

JS:

$scope.renderHtml = function(html_code)
{
    return $sce.trustAsHtml(html_code);
};
     

HTML:

<p ng-bind-html="renderHtml(value.button)"></p>

编辑:

这是设置:

JS档案:

angular.module('MyModule').controller('MyController', ['$scope', '$http', '$sce',
    function ($scope, $http, $sce) {
        $scope.renderHtml = function (htmlCode) {
            return $sce.trustAsHtml(htmlCode);
        };

        $scope.body = '<div style="width:200px; height:200px; border:1px solid blue;"></div>'; 

    }]);

HTML文件:

<div ng-controller="MyController">
    <div ng-bind-html="renderHtml(body)"></div>
</div>

答案 3 :(得分:63)

幸运的是,您不需要任何花哨的过滤器或不安全的方法来避免该错误消息。这是以预期和安全的方式在视图中正确输出HTML标记的完整实现。

必须在Angular之后包含sanitize模块:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-sanitize.js"></script>

然后,必须加载模块:

angular.module('app', [
  'ngSanitize'
]);

这将允许您在控制器,指令等的字符串中包含标记:

scope.message = "<strong>42</strong> is the <em>answer</em>.";

最后,在模板中,它必须像这样输出:

<p ng-bind-html="message"></p>

哪个会产生预期的输出: 42 答案

答案 4 :(得分:61)

我今天尝试过,我找到的唯一方法就是这个

<div ng-bind-html-unsafe="expression"></div>

答案 5 :(得分:51)

ng-bind-html-unsafe不再有效。

这是最短的方式:

创建过滤器:

myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

在您看来:

<div ng-bind-html="customHtml | unsafe"></div>

P.S。此方法不要求您包含ngSanitize模块。

答案 6 :(得分:25)

on html

<div ng-controller="myAppController as myCtrl">

<div ng-bind-html-unsafe="myCtrl.comment.msg"></div>

OR

<div ng-bind-html="myCtrl.comment.msg"></div
控制器上的

mySceApp.controller("myAppController", function myAppController( $sce) {

this.myCtrl.comment.msg = $sce.trustAsHtml(html);

也适用于$scope.comment.msg = $sce.trustAsHtml(html);

答案 7 :(得分:16)

As of Angular 4, this is the way that now works:

<div [innerHTML]="htmlString">
</div>

Taken from this question: Angular HTML binding

答案 8 :(得分:9)

我发现使用ng-sanitize不允许我在html中添加ng-click。

为了解决这个问题,我添加了一个指令。像这样:

app.directive('htmldiv', function($compile, $parse) {
return {
  restrict: 'E',
  link: function(scope, element, attr) {
    scope.$watch(attr.content, function() {
      element.html($parse(attr.content)(scope));
      $compile(element.contents())(scope);
    }, true);
  }
}
});

这是HTML:

<htmldiv content="theContent"></htmldiv>
祝你好运。

答案 9 :(得分:6)

只需按照angular(v1.4) docs

使用ngBindHtml执行此操作
<div ng-bind-html="expression"></div> 
and expression can be "<ul><li>render me please</li></ul>"

确保在模块的依赖项中包含ngSanitize。 然后它应该工作正常。

答案 10 :(得分:4)

另一种解决方案,与blrbr非常相似,只是使用了scoped属性:

angular.module('app')
.directive('renderHtml', ['$compile', function ($compile) {
    return {
      restrict: 'E',
      scope: {
        html: '='
      },
      link: function postLink(scope, element, attrs) {

          function appendHtml() {
              if(scope.html) {
                  var newElement = angular.element(scope.html);
                  $compile(newElement)(scope);
                  element.append(newElement);
              }
          }

          scope.$watch(function() { return scope.html }, appendHtml);
      }
    };
  }]);

然后

<render-html html="htmlAsString"></render-html>

请注意,您可以将element.append()替换为element.replaceWith()

答案 11 :(得分:3)

使用角度创建新的属性或指令,还有一个解决此问题的方法。

product-specs.html

 <h4>Specs</h4>
        <ul class="list-unstyled">
          <li>
            <strong>Shine</strong>
            : {{product.shine}}</li>
          <li>
            <strong>Faces</strong>
            : {{product.faces}}</li>
          <li>
            <strong>Rarity</strong>
            : {{product.rarity}}</li>
          <li>
            <strong>Color</strong>
            : {{product.color}}</li>
        </ul>

<强> app.js

 (function() {
var app = angular.module('gemStore', []);    
app.directive("     <div ng-show="tab.isSet(2)" product-specs>", function() {
return {
  restrict: 'E',
  templateUrl: "product-specs.html"
};
});

<强> 的index.html

 <div>
 <product-specs>  </product-specs>//it will load product-specs.html file here.
 </div>

<div  product-specs>//it will add product-specs.html file 

<div ng-include="product-description.html"></div>

https://docs.angularjs.org/guide/directive

答案 12 :(得分:3)

您还可以使用 ng-include

<div class="col-sm-9 TabContent_container" ng-include="template/custom.html">
</div>

您可以使用 “ng-show” 来显示隐藏此模板数据。

答案 13 :(得分:1)

使用

<div ng-bind-html="customHtml"></div>

angular.module('MyApp', ['ngSanitize']);

为此,您需要包含angular-sanitize.js, 例如在带有

的html文件中
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-sanitize.js"></script>

答案 14 :(得分:1)

这里是解决方案制作这样的过滤器

.filter('trusted',
   function($sce) {
     return function(ss) {
       return $sce.trustAsHtml(ss)
     };
   }
)

并将其作为过滤器应用于ng-bind-html,如

<div ng-bind-html="code | trusted">

感谢Ruben Decrop

答案 15 :(得分:0)

这是一个简单(且不安全)的bind-as-html指令,无需ngSanitize

myModule.directive('bindAsHtml', function () {
    return {
        link: function (scope, element, attributes) {
            element.html(scope.$eval(attributes.bindAsHtml));
        }
    };
});

请注意,如果绑定不受信任的内容,则会出现安全问题。

像这样使用:

<div bind-as-html="someHtmlInScope"></div>

答案 16 :(得分:-1)

使用管道的工作示例,使用Angular 4在模板中显示html。

1.Crated Pipe escape-html.pipe.ts

`

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name : 'keepHtml', pure : false})
export class EscapeHtmlPipe implements PipeTransform{
 constructor(private sanitizer : DomSanitizer){
 }
 transform(content){
  return this.sanitizer.bypassSecurityTrustHtml(content);
 }
}

` 2.将管道注册到app.module.ts

 import {EscapeHtmlPipe} from './components/pipes/escape-html.pipe';
    declarations: [...,EscapeHtmlPipe]
  1. 在模板中使用

    &#13;
    &#13;
        <div class="demoPipe"  [innerHtml]="getDivHtml(obj.header) | keepHtml">
    &#13;
    &#13;
    &#13;

  2. getDivHtml() { //can return html as per requirement}

    请在关联的component.ts文件中添加适当的getDivHtml实现。

答案 17 :(得分:-1)

只需使用[innerHTML],如下所示:

<div [innerHTML]="htmlString"></div>

在需要使用ng-bind-html ...

之前

答案 18 :(得分:-1)

在Angular 7 + ionic 4中,可以使用“ [innerHTML]”显示HTML内容:

<div [innerHTML]="htmlContent"></div>

希望,这也会对您有所帮助。谢谢。