Wscats / articles

🔖My Learning Notes and Memories - 分享我的学习片段和与你的回忆

Home Page:https://github.com/Wscats/articles

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Angular处理Html转义问题

Wscats opened this issue · comments

angular用$sce服务来过滤HTML标签
先看这个教程,再往下看~
http://www.w3cscript.com/Angular/2014-11-26/1.html

$scope.shareTips = data.data;//后台返回的数据赋个值吧
$scope.shareTipss = '1、Eno Yao;<br/>2、WsCats';
$scope.shareTips.rule_content = $sce.trustAsHtml($scope.shareTips.rule_content);//这里发现还是不行,难道姿势不对吗,纠结中~
console.log($scope.shareTips.rule_content);//测试返回的是空对象
$scope.shareTips.rule_content = $scope.shareTips.rule_content.replace(/\r?\n/g, "<br />");//换用正则解决,把所有\n换成<br />,是可以的
console.log($scope.shareTips.rule_content);//这里返回的字符串已经把\n换成<br />的

这里有两点细节很重要:
首先记得用$sce.trustAsHtml要先注入

angular.module('App').controller('ShareTipsCtrl', ['$rootScope', '$scope', 'Request', '$cookies', '$window', '$routeParams', '$location', '$sce',
    function($rootScope, $scope, request, $cookies, $window, $routeParams, $location, $sce) { //测试$sce
}]);

其次就是View渲染的时候
不要用
<p>{{$scope.shareTips.rule_content}}</p>
这里返回
会被ng安全处理的
用这个吧
<p ng-bind-html="shareTips.rule_content"></p>
后面我有时间会补充中...

20160426更新
最近调试了支付宝的网页支付的时候终于把这个问题解决了
由于支付宝的demo是后台生成一个DOM来返回的,所以在ng中我直接拿这部分数据渲染到浏览器上就可以了

angular.module('AswsTest').controller('OrderAliPayCtrl', ['$rootScope', '$scope', 'Request', '$cookies', '$window', '$routeParams', '$location', 'Tool', '$sce',
    function($rootScope, $scope, request, $cookies, $window, $routeParams, $location, tool , $sce) { 
        console.log($rootScope.alipayDom.order_string);
        $scope.dom = $sce.trustAsHtml($rootScope.alipayDom.order_string);
    }
])
<div ng-bind-html="dom">
</div>

这里ng-bind-html$sce是配合使用的,实践中缺一不可记得噢
image
然后成功渲染出这个页面