将AngularJS标签中的字符串转换为HTML

4

我有一个Angular代码片段,想把字符串转换成HTML对象。

 `<div class="row">
     <label class="col-md-4 info_text">Remarks<span>:</span></label> <label
      class="col-md-8 fieldValue">{{initialTableInfo.comments}}
     </label>
    </div>`

initialTableInfo.comments 的值为 <b>someText</b>。它被打印出来的时候与原样一致。我希望能够将 "someText" 以 someText 的形式打印,而不是 <b>someText</b>

3个回答

9
您可以在Angular中使用$sce参数。
module.controller('myctrl', ['$scope', '$http', '$sce',function($scope, $http, $sce) {

$scope.initialTableInfo.comments = $sce.trustAsHtml("<b>Some Text<b>");

}]);

在你的HTML中使用ng-bind-html
<label class="col-md-8 fieldValue" ng-bind-html="initialTableInfo.comment"> </label>

谢谢alexi-coard - 你让我的一天变得美好! - Gail Foad

3
您可以使用$sce.trustAsHtml(html)将字符串呈现为HTML,并使用ng-bind-html

DEMO

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.initialTableInfo ={};
$scope.initialTableInfo.comments =  '<b>someText</b>';
})

.filter('trustHtml',function($sce){
  return function(html){
    return $sce.trustAsHtml(html)
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div class="background-white p20 reasons"  >
    <h6><b>About {{aboutlongs[0].name}}</b></h6>
    <div class="reason-content" ng-bind-html="$scope.initialTableInfo.comments | trustHtml" >
     
    </div>
</div>
</div>


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接