从AngularJS控制器将HTML插入视图

从AngularJS控制器将HTML插入视图

本文介绍了从AngularJS控制器将HTML插入视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to create an HTML fragment in an AngularJS controller and have this HTML shown in the view?

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

This comes from a requirement to turn an inconsistent JSON blob into a nested list of id: value pairs. Therefore the HTML is created in the controller and I am now looking to display it.

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

I have created a model property, but cannot render this in the view without it just printing the HTML.

更新

问题似乎出在将创建的HTML角化为引号内的字符串而引起.会尝试找到解决此问题的方法.

It appears that the problem arises from angular rendering the created HTML as a string within quotes. Will attempt to find a way around this.

示例控制器:

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:

For Angular 1.x, use ng-bind-html in the HTML:

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

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

At this point you would get a attempting to use an unsafe value in a safe context error so you need to either use ngSanitize or $sce to resolve that.

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

Use $sce.trustAsHtml() in the controller to convert the html string.

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

ngSanitize

有2个步骤:

ngSanitize

There are 2 steps:

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

  1. include the angular-sanitize.min.js resource, i.e.:
    <script src="lib/angular/angular-sanitize.min.js"></script>

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

In a js file (controller or usually app.js), include ngSanitize, i.e.:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])

这篇关于从AngularJS控制器将HTML插入视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 04:55