AngularJS:插入HTML进入视野 [英] AngularJS : Insert HTML into view

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

问题描述

是否有可能在一个角控制器创建一个HTML片段,并在视图中显示这个HTML?

这是来自一个要求把不一致的JSON一滴到 ID的嵌套列表:值对。因此,HTML是在控制器中创建和我现在正在显示它。

我创建了一个模型属性,但在视图,而不只是打印HTML无法呈现这一点。


更新

看来,问题的角度产生渲染创建的HTML作为引号中的字符串。将试图找到解决的办法。

例如控制器:

  VAR SomeController =功能(){    this.customHtml ='< UL><立GT;渲染我请< /立GT;< / UL>';
}

例视图:

 < D​​IV NG:绑定=customHtml>< / DIV>

给出:

 < D​​IV>
    < UL><立GT;使我请< /立GT;< / UL>中
< / DIV>


解决方案

有关角1.x中,使用 NG-绑定-HTML 中的HTML:

 < D​​IV NG绑定-HTML =thisCanBeusedInsideNgBindHtml>< / DIV>

在这一点上,你会得到一个试图在安全的前提下,所以你必须要么使用的错误=htt​​ps://开头的文档.angularjs.org / API / ngSanitize /服务/ $的sanitize> ngSanitize $ SCE ,以解决这个问题。

$ SCE

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

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

ngSanitize

有2个步骤:


  1. 包括角sanitize.min.js资源,即:结果
    <脚本SRC =LIB /角/角sanitize.min.js>< / SCRIPT>


  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 Angular 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天全站免登陆