美文网首页
使用ng-bind-html指令和$sce服务

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

作者: cshooting | 来源:发表于2017-09-02 23:54 被阅读0次

最近遇到后台返回的数据中带有各种各样的html标签,需要把返回的html内容插入到页面。在angular中,如果我们想要把它插入到页面中可以使ng-bind-html这个指令来实现。但是如果只是仅仅使用这个指令并不能达到我们所要的效果。angular中直接嵌入一段html代码会认为是不安全的,所以此时angular会给我们报错。
对于angular 1.2之后的版本我们必须要使用$sce这个服务来解决我们的问题。所谓sce即“Strict Contextual Escaping”的缩写。翻译成中文就是“严格的上下文模式”也可以理解为安全绑定吧。我们必须告诉它安全绑定。它可以通过使用$ sce.trustAsHtml()。该方法将值转换为特权所接受并能安全地使用“ng-bind-html”。所以,我们必须在我们的控制器中注入$sce服务。

html
<div ng-bind-html="test"></div>
script
var app=angular.module('app',[]);
app.controller('testCtrl',['$scope','$sce',function($scope){
    $scope.testHtml=<p class="color" ng-click="test()">hello world</p>;
    $scope.test=$sce.trustAsHtml($scope.Html);
}])
$scope.test=function(){
    alert(1);
}
css
.color{
     background-color:blue;
}

在div内能加载带有html标签的内容,标签的Css属性以及使用ng-click绑定在元素上的事件。

相关文章

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

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

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

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

  • angular输出html

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

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

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

  • Angular(二)

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

  • angularjs解决方案之 Error: [$sce:unsa

    标签:ng-bind-html angularjs中无法直接使用ng-bind-html: 错误截图: 代码如下:...

  • 指令

    ng 指令 ng-app ng-model ng-bind ng-bind-html ng-bind-templa...

  • AngularJS指令小结

    刚刚接触AngularJS,总结了一些关于AngularJS的基本指令。 1、 ng-bind-html 类似于h...

  • Nginx笔记(四)

    代理一组服务器 使用upstream指令来定义一组服务器,指令放在http context里如:http { ...

  • 自定义服务

    自定义服务和自定义指令,自定义过滤器写法类似,一共有 三种关键字 定义服务 使用服务必须注入,使用原生的服务注入方...

网友评论

      本文标题:使用ng-bind-html指令和$sce服务

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