angularjs中ng-bind-html使用问题
来源:互联网 发布:rpc动态端口 编辑:程序博客网 时间:2024/05/01 14:29
angular中的ng-bind-html指令和$sce服务
angular js的强大之处之一就是他的数据双向绑定这一牛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>
0 0
- angularjs中ng-bind-html使用问题
- 解决AngularJS使用ng-bind-html会过滤html中style属性的问题
- 解决AngularJS使用ng-bind-html会过滤html中style属性的问题
- AngularJS使用ng-bind-html会过滤html中style属性的问题
- AngularJS 2 中如何实现ng-bind-html
- AngularJS 2 中如何实现ng-bind-html
- AngularJs ng-bind-html指令整理
- ng-bind-html 的使用
- angularjs ng-bind-html 指令 对html标签转译
- angularjs中ng-bind和ng-model用法
- AngularJS中ng-app、ng-model、ng-bind、ng-init、ng-repeat、自定义指令
- angularjs使用ng-repeat不用包含在html元素中
- angularjs使用ng-switch不用包含在html元素中
- angularJS 中html 标签绑定样式,ng-class的使用
- angularJS中把html格式的字符串转成html格式显示,ng-bind-html与trustAsHtml的过滤器
- angularJs 中的ng-bind-html指令和$sce服务
- 使用ng-bind-html标签 注意事项
- ng-bind-html和.$compile的使用
- 如何在DrawerLayout下为navigation Header上的控件添加监听事件
- apollo搭建安卓推送
- 大型分布式C++框架《二:大包处理过程》
- KeepAlived+DRDB+MFS安装及配置
- 向可变数组中添加元素崩溃。。。
- angularjs中ng-bind-html使用问题
- tar 解压
- laydate日期选择插件蓝色风格自定义及使用Demo
- django.db.utils.OperationalError: (1142, "REFERENCES command denied to user
- 官网翻译篇--在 SQL 数据库中保存数据
- js禁用和开启鼠标滚轮
- Unique Paths II
- Android开发之获取手机运行时间
- 关于Android Intent传值接受的问题