美文网首页
angular中的ng-bind-html指令和$sce服务

angular中的ng-bind-html指令和$sce服务

作者: 崠崠 | 来源:发表于2018-10-24 18:00 被阅读0次

转载自: 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>

相关文章

  • angular中的ng-bind-html指令和$sce服务

    转载自: angular中的ng-bind-html指令和$sce服务 angular js的强大之处之一就是他的...

  • angular输出html

    通过指令 ng-bind-html来实现html的输出 还需要通过通过$sce服务来实现html的展示 这里通过$...

  • 使用ng-bind-html指令和$sce服务

    最近遇到后台返回的数据中带有各种各样的html标签,需要把返回的html内容插入到页面。在angular中,如果我...

  • Angular(二)

    angular指令Directive $sce控制代码安全检查 为什么要要$sce?因为AngularJS里很多地...

  • angular 中的 $sce 服务

    AngularJS里好些地方,比如路径默认是个字符串,不会认为是路径,从而访问不到我们需要的东西,那么我们就可以通...

  • 使用$sce.trustAsHtml()解决Angularjs

    在开发中遇见了这个bug 调查发现导致错误的原因是文本里带了html标签,使用ng-bind-html和 $sce...

  • 自定义指令(上)

    简介 在常用指令的章节中我们讲了Angular提供的指令,这些指令是Angular内部封装好指令,我们开箱...

  • angular内置指令相关知识

    大纲 1、angular指令的分类2、angular指令之——组件3、angular指令之——属性指令 (ngSt...

  • angularjs中动态为audio绑定src

    1.常见audio的使用 2.angular.js中的绑定需要在对应的control中添加sce.trustAsR...

  • angular tanslate

    参考:https://angular-translate.github.io/ 引用 服务商 服务 过滤器 指令 ...

网友评论

      本文标题:angular中的ng-bind-html指令和$sce服务

      本文链接:https://www.haomeiwen.com/subject/smvxtqtx.html