美文网首页angular
使用$sce.trustAsHtml()解决Angularjs

使用$sce.trustAsHtml()解决Angularjs

作者: 壹只很拽的猫 | 来源:发表于2019-03-06 10:58 被阅读0次

在开发中遇见了这个bug

Error: [$sanitize:badparse] The sanitizer was unable to parse the following block of html:

调查发现导致错误的原因是文本里带了html标签,使用ng-bind-html$sce.trustAsHtml();来解决这个问题。

$scope.text= $sce.trustAsHtml($scope.text);

但是因为字符串里有\n\t等,使用$sce.trustAsHtml后文字无法换行,
我用了<br\>来替换字符串里的\n

$scope.test= $scope.test.replace(/\n/g,'<br>').replace(/\t/g,'&nbsp');
$scope.test= $sce.trustAsHtml($scope.test);

这样在第一次执行的时候是没问题的,但是如果执行第二次就报错了。
Error: $scope.test.replace is not a function
因为$scope.test不是字符串了变成Object了。判断一下如果是String才执行。

  if($scope.test && typeof $scope.test === 'string'){
        $scope.test= $scope.test.replace(/\n/g,'<br>').replace(/\t/g,'&nbsp');
        $scope.test= $sce.trustAsHtml($scope.test);
  }

以上就全部解决了我的问题。

---------------------------------------分割线----------------------------------------
后来发现了这篇文章,使用了filter更好的解决了我的问题,代码量更简洁。
angularjs中类似textarea的换行、空格处理
但是如果文本里包含尖括号类似于<xx>就会被当成HTML标签而不显示。那么在文本存入数据库前就要先进行字符转义。
$scope.t = $scope.t.replace(/</g,'&lt;').replace(/>/g,'&gt;');

filter 代码如下

// trustHtml filter
'use strict';
app.filter('trustHtml',function($sce){
    return function(input){
        function handlerStr(str) {
            var text =str.replace(/\n/g,'<br />').replace(/\t/g,'&nbsp');
            return text;
        }
        return $sce.trustAsHtml(handlerStr(input));
    };
});

字符串替换参考文章
如何用js替换文本里的换行符\n?

$sce.trustAsHtml参考文章
Parse an HTML document with AngularJS
angular ng-bind-html $sce.trustAsHtml
深究AngularJS——$sce的使用
angular源码分析:angular中入境检察官$sce

相关文章

网友评论

    本文标题:使用$sce.trustAsHtml()解决Angularjs

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