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

当前回答

下面是解决方案,制作一个这样的过滤器

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

并将其作为过滤器应用于ng绑定html

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

感谢鲁本·德洛普

其他回答

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

这是最短的路:

创建筛选器:

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

在您看来:

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

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

我今天试过了,唯一找到的办法就是

<div ng bind html unsafe=“expression”></div>

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

Angular:

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

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

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

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

只是通过遵循angular(v1.4)文档使用ngBindHtml实现了这一点,

<div ng-bind-html="expression"></div> 
and expression can be "<ul><li>render me please</li></ul>"

确保在模块的依赖项中包含ngSanitize。那么它应该工作得很好。