有没有办法使用ng-bind-html绑定纯文本

时间:2018-05-29 06:08:44

标签: html angularjs

我正在使用带有段落标记的Label.addCart{ text-align: right; color: rgb(220, 220, 220); margin-right: 15px; margin-bottom: 0px; font-size: 15px; font-family: "FontAwesome"; } 。例如

ng-bind-html

当我在Message中获取html时,它正在按预期工作,但是当它是纯文本时,它不会呈现消息。有人能解释一下原因吗?消息可能包含Html或可能不包含。任何帮助都会很明显

2 个答案:

答案 0 :(得分:1)

试用ngSanitize模块。 Here is the plunkr,尝试removing模块注入并查看行为

<!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>

<script>
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "My name is: John Doe";
});
</script>

<p><b>Note:</b> This example includes the "angular-sanitize.js",
which has functions for removing potentially dangerous tokens from the HTML.</p>

</body>
</html>

答案 1 :(得分:1)

您可以在不使用其他模块的情况下使用trustAsHtml过滤器,

<强>样本

&#13;
&#13;
var app = angular.module("exApp",["ngSanitize"]);

app.controller('ctrl', function($scope, $sce){
$scope.message = $sce.trustAsHtml('Hello this is text <a href="#">Kristoff</a> ' +
     'this is my domain <a href="http://www.website.com/">www.website.com</a>');
$scope.messageplain = $sce.trustAsHtml("Hellow");
 
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-sanitize.min.js"></script>
<body ng-app="exApp">
<div ng-controller="ctrl">
<span ng-bind-html="message"></span>
 
<span ng-bind-html="messageplain"></span>
 
</div>
</body>
&#13;
&#13;
&#13;