是否可以在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(v1.4)文档使用ngBindHtml实现了这一点,

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

确保在模块的依赖项中包含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);

Angular JS在标记中显示HTML

上面的链接中提供的解决方案对我有效,但这个线程上的选项都没有。对于任何希望使用AngularJS版本1.2.9实现相同功能的人

这是一份副本:

好的,我找到了解决方案:JS文件:$scope.renderHtml=函数(html_code){返回$scetrustAsHtml(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>

对于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”])

我发现使用ng消毒液不允许我在html中添加ng点击。

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

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>

祝你好运

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

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