1. 程式人生 > >解決AngularJS使用ng-bind-html會過濾html中style屬性的問題

解決AngularJS使用ng-bind-html會過濾html中style屬性的問題

要輸出一個包含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格式的字串。

這樣就可以顯示出所需要的樣式了。