我们可以在“过滤器”中使用$ sce.trustAsHtml(字符串)吗?

时间:2013-12-11 13:48:08

标签: angularjs

HTML:

<div ng-app="app">
  <test-d class="my-class">this should be replaced</test-d>
</div>

JS:

    angular.module('app', []).directive('testD', ['$compile','$sce', function($compile, $sce) {
        return {
            restrict: 'E',
            link: function(scope, element, attrs, controller) {

                //"case 1"
                //var testElement = angular.element('<div class="{{testClass}}"><div ng-repeat="item in items">{{item.n}}.{{item.label}}</div></div>');

                //"case 2"
                var testElement = angular.element('<div class="{{testClass}}"><div ng-repeat="item in items">{{item.n}}<div class="how-to-remove-this-div" ng-bind-html="item.label|htmlize"></div></div></div>');

                scope.testClass = attrs.class;

                scope.items = [
                    //{n:10,label:$sce.trustAsHtml('<span class="with-icon">label 11</span>')},
                    // "case 1" of "testElement": no any effects (with "case 1" that would be preferred)
                    // "case 2" of "testElement": Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html

                    {n:20,label:'<span class="with-icon">label 22</span>'},
                    {n:30,label:'<span class="with-icon">label 33</span>'}
                ];

                var testElementCompiled = $compile(testElement)(scope);

                //"case 3"
                element.replaceWith(testElementCompiled);

                //"case 4"
                //element.replaceWith($sce.trustAsHtml(testElementCompiled));
            }
        }
}]).filter('htmlize', ['$sce', function($sce){
        return function(val) {
            return $sce.trustAsHtml(val);
        };
}]);

的jsfiddle: http://jsfiddle.net/isnigirev/c2wRq/

问题: 1)是否可以在过滤器上下文中使用trustAsHtml? 2)如果不使用“ng-bind-html”指令,如何使用“how-to-remove-this-div”类除掉div?

2 个答案:

答案 0 :(得分:11)

得到它(trustAsHtml)在指令here中工作。当我错误地尝试在同一个“标签”上调用trustAsHtml两次时发生"Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html"错误。

问题的第二部分仍然存在,但我将通过一些解决方法解决它。无论如何,解决它也很有趣。

答案 1 :(得分:4)

文章是要显示的文字

<div ng-app="app">
<span data-ng-bind-html="article| to_trusted"></span>
</div>

并过滤为:

 app.filter('to_trusted', ['$sce', function($sce){
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]);