【问题标题】:Angularjs html tags showing instead of renderingAngularjs html标签显示而不是渲染
【发布时间】:2018-04-25 09:50:00
【问题描述】:

我有以下变量:

$scope.someVar= "Some<br>text<br>here";

当我在 HTML 文档中使用 {{ someVar }} 调用它时,我得到以下输出:

Some&lt;br&gt;text&lt;br&gt;here

我想要以下输出:

一些
文本
这里

我该怎么做才能渲染 HTML 代码?

提前感谢您的所有建议。

【问题讨论】:

  • 使用来自ngSanitize 模块的ng-bind-html。你也可以通过指令$compile
  • 嗨@AlekseySolovey,感谢您的回复。我刚开始使用angularjs。不知道如何使用它,但如果我没记错的话,我需要按照以下方式进行操作:。我可以用 {{someVar}} 代码以某种方式应用它吗?

标签: html angularjs rendering


【解决方案1】:

您可以使用ng-bind-html

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "My name is: <h3>John Doe</h3>";
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-sanitize.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<p ng-bind-html="myText"></p>

</div>

</body>
</html>

【讨论】:

  • 谢谢@VipulSolanki 成功了。在调用括号之间的变量({{someVar}})时,是否可以使用ng-bind-html?还是我必须使用 HTML 标签?
  • 喜欢这个&lt;p&gt;(&lt;ng-bind-html ng-bind-html="myText"&gt;&lt;/ng-bind-html&gt;)&lt;/p&gt; ?还是你想在函数中使用这个变量?
  • 我现在有这样的:&lt;p&gt;{{ varOne }} {{ varTwo }} &lt;span ng-bind-html="varThree"&gt;&lt;/span&gt;&lt;/p&gt;,并希望有&lt;p&gt;{{ varOne}} {{ varTwo }} {{ varThree }}&lt;/p&gt;。如果可能的话。 varOne 和 varTwo 工作正常,因为它们没有 HTML 标记。
  • 是的,你可以。如果varOnevarTwo 可能有html 值,你可以使用&lt;p&gt;&lt;span ng-bind-html="varOne"&gt;&lt;/span&gt; &lt;span ng-bind-html="varTwo"&gt;&lt;/span&gt; &lt;span ng-bind-html="varThree"&gt;&lt;/span&gt;&lt;/p&gt;。如果变量有 html 代码,它会转换,否则它会返回实际值。
【解决方案2】:

其他解决方案:
你可以使用 $sce,
示例:
html:

<div ng-app="testApp" ng-controller="testController">
    <p ng-bind-html="someVar"></p>
</div>

js:

var app = angular.module('testApp', []);

app.controller('testController', ['$sce', '$scope', function($sce, $scope) {

    $scope.someVar =  $sce.trustAsHtml("Some<br>text<br>here");
}]);

【讨论】:

    猜你喜欢
    • 2014-05-17
    • 1970-01-01
    • 2013-10-29
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多