如何显示angularjs模板,而不是字符串的html? [英] How to show html in angularjs template instead of string?

查看:93
本文介绍了如何显示angularjs模板,而不是字符串的html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量在我的范围:

I have a variable in my scope:

$scope.myvar = "Hello<br><br>World"

在我的模板我使用的:

<div>{{myvar}}</div>

问题是MYVAR显示文字文本,而我想让它显示的换行符。如何做到这一点?请注意,我想让它这样的,如果我在未来,MYVAR得到与其他HTML更新,然后显示在页面上应该是什么编译HTML而不是文字串在它的HTML标记。

The issue is myvar shows the literal text, whereas I want it to show the line breaks. How to do this? Note that I want to make it such that if I in the future, myvar gets updated with other HTML, then what is shown on the page should be the "compiled" html as opposed to the literal string with the html tags in it.

推荐答案

您可以使用 ngBindHtml 作为这一点。结果
请记住,由于角度的 严格的概念逃逸 内容必须要么消毒(使用产生额外的模块 ngSanitize )或明确地trustedAsHtml(使用 $ sce.trustAsHtml())。后者被认为只为你内容要使用知道是安全的(例如没有用户自定义),反正是不推荐的。

You can use ngBindHtml for that.
Keep in mind that due to Angular's Strict Conceptual Escaping the content needs to be either sanitized (using the additonal module ngSanitize) or explicitely "trustedAsHtml" (using $sce.trustAsHtml()). The latter is supposed to be used only for content you know is safe (e.g. nothing user defined) and is not recommended anyway.

<子>
注意: ngSanitize 是一个非核心模块,并应分别包括:结果
    &LT; SCRIPT SRC =... / angular.min.js&GT;&LT; / SCRIPT&GT; 结果
    &LT; SCRIPT SRC =... /角sanitize.min.js&GT;&LT; / SCRIPT&GT;

Note: ngSanitize is an non-core module and should be included separately:
<script src=".../angular.min.js"></script>
<script src=".../angular-sanitize.min.js"></script>

例如:

/* Using ngSanitize */
angular.module('app', ['ngSanitize'])
.controller('myCtrl', function ($scope) {
    $scope.myHtml = 'Hello<br /><br />world !';
});

/* Using $sce.trustAsHtml() */
angular.module('app', [])
.controller('myCtrl', function ($sce, $scope) {
    $scope.myHtml = $sce.trustAsHtml('Hello<br /><br />world !');
});

<子>
需要注意的是 ngSanitize 将过滤不恰当的内容,而 $ sce.trustAsHtml 将允许任何东西。

Note that ngSanitize will filter "non-appropriate" content, while $sce.trustAsHtml will allow anything.

又见这个 短演示

See, also, this short demo.

这篇关于如何显示angularjs模板,而不是字符串的html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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