从 AngularJS 控制器将 HTML 插入视图 [英] Insert HTML into view from AngularJS controller

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

问题描述

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

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

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

<小时>

更新

问题似乎是由于将创建的 HTML 角度渲染为引号内的字符串引起的.将尝试找到解决此问题的方法.

示例控制器:

var SomeController = function () {this.customHtml = '<ul><li>请渲染我</li></ul>';}

示例视图:

给出:

<ul><li>请渲染我</li></ul>"

解决方案

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

此时您会收到 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 资源,即:

  2. 在 js 文件(控制器或通常是 app.js)中,包含 ngSanitize,即:

    angular.module('myApp', ['myApp.filters', 'myApp.services','myApp.directives', 'ngSanitize'])

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

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.

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


Update

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.

Example controller :

var SomeController = function () {

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

Example view :

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

Gives :

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

解决方案

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

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

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

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

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

ngSanitize

There are 2 steps:

  1. include the angular-sanitize.min.js resource, i.e.:

    <script src="lib/angular/angular-sanitize.min.js"></script>
    

  2. 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 插入视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆