源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-02-09 15:29 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:深入理解AngularJS中的ng-bind-html指令和$sce服务
[b]前言 [/b] Angularjs的强大之处之一就是他的数据双向绑定这一牛B功能,我们会常常用到的两个东西就是ng-bind和针对form的ng-model。 但在我们的项目当中会遇到这样的情况,后台返回的数据中带有各种各样的html标签。 [b]如:[/b]
$scope.currentWork.description = “hello,<br><b>今天我们去哪里?</b>”
我们用ng-bind-html这样的指令来绑定,结果却不是我们想要的。 是这样的
hello,
今天我们去哪里?
怎么办呢? 对于angular 1.2一下的版本我们必须要使用$sce这个服务来解决我们的问题。所谓sce即“Strict Contextual Escaping”的缩写。翻译成中文就是“严格的上下文模式”也可以理解为安全绑定吧。 来看看怎么用吧。 [b]controller code:[/b]
$http.get('/api/work/get?workId=' + $routeParams.workId).success(function (work) {$scope.currentWork = work;});
[b]HTML code:[/b]
<p> {{currentWork.description}}</p>
我们返回的内容中包含一系列的html标记。表现出来的结果就如我们文章开头所说的那样。这时候我们必须告诉它安全绑定。它可以通过使用[code]$ sce.trustAsHtml() [/code]。该方法将值转换为特权所接受并能安全地使用“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);
});
[b]html code:[/b]
<p ng-bind-html="currentWork.description"></p>
这样结果就完美的呈现在页面上了:
hello 
今天我们去哪里?
咱们还可以这样用,把它封装成一个过滤器就可以在模板上随时调用了
app.filter('to_trusted', ['$sce', function ($sce) {
return function (text) {
 return $sce.trustAsHtml(text);
};
}]);
[b]html code:[/b]
<p ng-bind-html="currentWork.description | to_trusted"></p>
[b]总结[/b] 以上就是关于AngularJS中的ng-bind-html指令和$sce服务的全部内容了,希望对大家的学习或者工作带来一定的帮助,如果有问题可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部