如何使用ng-bind-html?

时间:2014-12-13 22:47:05

标签: angularjs

为什么这种绑定没有任何想法?

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

function MyCtrl($scope) {
  $scope.myHTML = "<a href='#'>a link</a>";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-controller="MyCtrl">
  <p ng-bind-html="myHTML"></p>
</div>

1 个答案:

答案 0 :(得分:5)

要使HTML绑定生效,您的模块需要注入ngSanitize以及包含的文件angular-sanitize(.min).js

&#13;
&#13;
var myApp = angular.module('myApp',['ngSanitize']);

function MyCtrl($scope) {
  $scope.myHTML = "<a href='#'>a link</a>";
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular-sanitize.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  <p ng-bind-html="myHTML"></p>
</div>
&#13;
&#13;
&#13;

或者你可以使用String Contextual Escaping(在未来的Angular版本中可能会 的方式)。