深入理解AngularJS中的ng-bind-html指令和$sce服务

2019-11-30,,,,,,,

前言

Angularjs的强大之处之一就是他的数据双向绑定这一牛B功能,我们会常常用到的两个东西就是ng-bind和针对form的ng-model。

但在我们的项目当中会遇到这样的情况,后台返回的数据中带有各种各样的html标签。

如:

$scope.currentWork.description = “hello,<br><b>今天我们去哪里?</b>”

我们用ng-bind-html这样的指令来绑定,结果却不是我们想要的。

是这样的

hello,
今天我们去哪里?

怎么办呢?

对于angular 1.2一下的版本我们必须要使用$sce这个服务来解决我们的问题。所谓sce即“Strict Contextual Escaping”的缩写。翻译成中文就是“严格的上下文模式”也可以理解为安全绑定吧。

来看看怎么用吧。

controller code:

$http.get('/api/work/get?workId=' + $routeParams.workId).success(function (work) {$scope.currentWork = work;});

HTML code:

<p> {{currentWork.description}}</p>

我们返回的内容中包含一系列的html标记。表现出来的结果就如我们文章开头所说的那样。这时候我们必须告诉它安全绑定。它可以通过使用$ sce.trustAsHtml() 。该方法将值转换为特权所接受并能安全地使用“ng-bind-html”。所以,我们必须在我们的控制器中引入$sce服务

controller('transferWorkStep2', ['$scope','$http','$routeParams','$sce', function ($scope,$http, $routeParams, $sce) {
$http.get('/api/work/get?workId=' + $routeParams.workId)
.success(function (work) {
 $scope.currentWork = work;
 $scope.currentWork.description = $sce.trustAsHtml($rootScope.currentWork.description);
});

html code:

<p ng-bind-html="currentWork.description"></p>

这样结果就完美的呈现在页面上了:

hello 
今天我们去哪里?

咱们还可以这样用,把它封装成一个过滤器就可以在模板上随时调用了

app.filter('to_trusted', ['$sce', function ($sce) {
return function (text) {
 return $sce.trustAsHtml(text);
};
}]);

html code:

<p ng-bind-html="currentWork.description | to_trusted"></p>

总结

以上就是关于AngularJS中的ng-bind-html指令和$sce服务的全部内容了,希望对大家的学习或者工作带来一定的帮助,如果有问题可以留言交流。

您可能感兴趣的文章:

  • AngularJS通过$sce输出html的方法
  • 详解AngularJs中$sce与$sceDelegate上下文转义服务
  • AngularJS 使用$sce控制代码安全检查
  • 深究AngularJS中$sce的使用

《深入理解AngularJS中的ng-bind-html指令和$sce服务.doc》

下载本文的Word格式文档,以方便收藏与打印。