是否可以在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>

当前回答

对于Angular 1.x,在html中使用ng bind html:

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

此时,您将尝试在安全上下文错误中使用不安全的值,因此需要使用ngSanitize或$sce来解决此问题。

$sce

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

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

ngSanitize公司

有两个步骤:

包括angular-cleanity.min.js资源,即:<script src=“lib/aangular/aangular cleanity.min.js”></script>在js文件(controller或通常是app.js)中,包含ngSanitize,即:angular.module('myApp',['myApp.filters','myApp.services',“myApp.指令”,“ngSanitize”])

其他回答

在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.coment.msg=$sce.trustAsHtml(html);

ng绑定html不安全不再有效。

这是最短的路:

创建筛选器:

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

在您看来:

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

注:此方法不需要包含ngSanitize模块。

只需简单使用[ninnerHTML],如下所示:

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

在您需要使用ng绑定html之前。。。

也可以使用nginclude。

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

您可以使用“ngshow”显示隐藏此模板数据。

您也可以创建如下过滤器:

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漏洞。