angular中的ng-bind-html指令和$sce服务
来源:互联网 发布:python执行批处理命令 编辑:程序博客网 时间:2024/04/29 00:42
Error: [$sce:unsafe] http://errors.angularjs.org/1.4.10/$sce/unsafe
遇到此bug 查询原因ng-bind-html的使用
遇到此bug 查询原因ng-bind-html的使用
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
- angular中的ng-bind-html指令和$sce服务
- angular中的ng-bind-html指令和$sce服务
- angular中的ng-bind-html指令和$sce服务
- angular中的ng-bind-html指令和$sce服务
- angularJs 中的ng-bind-html指令和$sce服务
- 用ng-bind-html指令和 $sce服务 实现页面输出html
- angular1.x 中的$sce/ng-bind-html用法
- Angular指令之ng-bind-html
- ng-bind-html指令
- ng-bind-html指令
- Angular中的ng-bind和ng-model区别
- 关于ng-bind-html 指令
- (四上)Angular指令,ng-bind指令,ng-init 指令,ng-click指令,ng-repeat 指令
- AngularJs ng-bind-html指令整理
- angular中ng-bind和ng-model的区别
- angular中ng-bind和ng-model的区别
- angular循环生成iconfont字体(ng-bind-html)
- React的dangerouslySetInnerHTML与Angular的ng-bind-html
- Spring MVC 入门示例讲解
- JS获取表单数据
- 11年福州 F 次小生成树变形 树形DP
- MySQL5.7重置root密码
- 长按listview弹出上下文菜单实现
- angular中的ng-bind-html指令和$sce服务
- EL和JSTL的总结(一)
- 包
- FFmpeg源代码简单分析:常见结构体的初始化和销毁(AVFormatContext,AVFrame等)
- 多线程
- 回溯法迷宫求解
- C++语言笔试题目 所有的运算符都能重载吗&不用if结构,找出两个变量之间的最大值等
- 反射
- 反射