解决AngularJS使用ng-bind-html会过滤html中style属性的问题

来源:互联网 发布:部落冲突亡灵升级数据 编辑:程序博客网 时间:2024/04/18 18:21

要输出一个包含html格式效果的文本就是字符串

众所周知,就是要通过ng-bind-html来进行数据绑定

<small class="block m-t-sm img-full" data-ng-bind-html="vm.contentdetial.content" ></small>

首先一个简单的例子输出字符串“hello<br>AngularJS”

我们期待的结果是:

hello

angularJS

如果只是普通的使用{{}}进行数据绑定,显然无法识别转义html,输出结果即为:

hello<br>angularJS

字符串内容。

现在已经了解ng-bind-html的效果了,那么现在升级一步,我们给字符串中的html标签加入样式。(原谅我找了一个看起来很复杂的例子。。。)

<section style="border: 0px; margin: 0.8em 0px 0.5em; box-sizing: border-box; padding: 0px;" class="tn-Powered-by-XIUMI"><span style="display: inline-block; padding: 0.3em 0.5em; border-radius: 0.5em; color: rgb(255, 255, 255); font-size: 1em; box-shadow: rgb(165, 165, 165) 0.2em 0.2em 0.1em; font-family: inherit; text-decoration: inherit; border-color: rgb(249, 110, 87); box-sizing: border-box; background-color: rgb(249, 110, 87);" class="tn-Powered-by-XIUMI"><section class="tn-Powered-by-XIUMI" style="box-sizing: border-box;">请输入标题</section></span><section style="width: 0px; height: 0px; clear: both;"></section></section>

请输入标题

而使用ng-bind-html显示的结果那就~~~~

请输入标题

你没有看错,竟然只显示出了文字,没有样式,审查元素看看是什么情况

<section class="tn-Powered-by-XIUMI"><span class="tn-Powered-by-XIUMI"><section class="tn-Powered-by-XIUMI">请输入标题</section></span><section></section></section>

问题显而易见了,所有的style被过滤了,或者说是忽略了,没有展示出来。那么现在就要解决这个问题了。

我就展示我公司项目的代码了,在页面相应的controller.js中使用$sce.trustAsHtml()

(function () {

    var injectParams = ['$scope', '$location', '$routeParams',
                        '$timeout', 'config', 'dataService','toaster','$sce' ];

    var ContentController = function ($scope, $location, $routeParams,
                                           $timeout, config, dataService,toaster,$sce) {
        var vm = this,
            contentId = ($routeParams.contentId) ? parseInt($routeParams.contentId) : 0,
            timer,
            onRouteChangeOff;
        vm.contentdetial = {};
        
        function getContent() {
            dataService.getContent(contentId)
            .then(function (data) {
            vm.contentdetial = data;
            vm.contentdetial.content = $sce.trustAsHtml(data.content);


                $timeout(function () {
                }, 1000);
            }, function (error) {
                toaster.pop('warning', "处理失败", "很遗憾处理失败,由于网络原因无法连接到服务器!");
            });
        }
        
        function init() {
        getContent();
        }
        init();
    };

    ContentController.$inject = injectParams;
    angular.module('serviceApp').controller('ContentController', ContentController);
   
}());


解决方法就是在controller中给数据也就是要显示的内容字符串使用$sce.trustAsHtml()

            vm.contentdetial.content = $sce.trustAsHtml(data.content);

data.content就是带html格式的字符串。

这样就可以显示出所需要的样式了。

0 0
原创粉丝点击