Angular bind-html + $ sce仍然删除内联样式

时间:2017-02-22 17:50:12

标签: html angularjs

我编写了一个返回字符串值的简单自定义过滤器。

该值包含html字符串和内联样式

绑定角度时删除样式

这是我的过滤器

siteApp.filter('specialText', ['$filter', '$sce', function ($filter, $sce) {
    return function (code, items, defaults) {
          var out = defaults;
          if (items && items.length) {
            var arr = $filter('filter')(items, { code: code }, true);
            if (arr && arr.length > 0) {
                out = arr[0].value;
                $sce.trustAsHtml(out);
            }
        }
        return out;
    };
}]);

这是我的HTML

 <div  ng-bind-html="'body_message' | specialText : specific_texts :''"></div>

原始文本包含内联样式,但在绑定时使用角度删除内联样式

enter image description here

如何保留内联样式

完整示例代码

&#13;
&#13;
<body >
    <div ng-app="siteApp">
        <div ng-controller="ctrl">
            {{'test1' | specialText : arr :'missing....' }}
            <div ng-bind-html="'test1' | specialText : arr :'missing....'"></div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.5.6/angular-sanitize.js"></script>
    <script>
        var siteApp = angular.module('siteApp', ['ngSanitize']);
        siteApp.filter('specialText', ['$filter', '$sce', function ($filter, $sce) {
            return function (code, items, defaults) {
                var out = defaults;
                if (items && items.length) {
                    var arr = $filter('filter')(items, { code: code }, true);
                    if (arr && arr.length > 0) {
                        out = arr[0].value;                      
                        $sce.trustAsHtml(out);
                    }
                }
                return out;
            };
        }]);
        siteApp.controller('ctrl', ['$scope', function ($scope) {
            $scope.arr = [{ "code": "test1", "rte": true, "value": "<p style=\"text-align: left;\">First Row</p>\n<h1 style=\"text-align: center;\">Second Center Row</h1>" }];
        }]);
    </script>
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您没有使用$sce.trustAsHtml(out)的输出。在您的if语句中尝试out = $sce.trustAsHtml(out);,应该没问题。