如何使用ng-bind-html?

4th*_*ace 3 angularjs

任何想法为什么这个绑定不起作用?

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

function MyCtrl($scope) {
  $scope.myHTML = "<a href='#'>a link</a>";
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Sho*_*omz 5

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

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

function MyCtrl($scope) {
  $scope.myHTML = "<a href='#'>a link</a>";
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

或者您可以使用String Contextual Escaping(这可能是在 Angular的未来版本中执行此操作的方法).