使用角度过滤器突出显示文本即使在使用trustAsHtml时也会抱怨$ sce不安全

时间:2016-10-04 07:11:45

标签: angularjs coffeescript highlight

我试图通过对它们应用角度过滤器来强调搜索到的单词,这些过滤器会动态添加span元素。我信任$sce的HTML,但我仍然收到错误:Error: [$sce:unsafe] http://errors.angularjs.org/1.4.7/$sce/unsafe

这就是我所拥有的(简化):

html元素:

<span ng-bind-html="entity.desc | filter:highlight(search)"></span>

指令:

scopePicker = ($sce) ->

    return {
        restrict: 'E'
        scope: {
            ...
        }
        templateUrl: 'my.html'
        link: (scope, element, attributes, controller) ->

            scope.highlight = (string) -> (desc) ->
                return trustAsHtml(desc) unless string
                return trustAsHtml(desc.replace(string, '<span class="highlighted">' + string + '</span>'))

            return
    }

angular
    .module('scopePicker')
    .directive('sScopePicker', ['$sce', scopePicker])

1 个答案:

答案 0 :(得分:0)

问题是我试图在范围内使用过滤功能。您需要将其与指令一起添加到模块级别。

我做了什么:

highlightFilter = ($sce) -> (desc, string) ->
    return $sce.trustAsHtml(desc) unless string
    return $sce.trustAsHtml(desc.replace(string, '<span class="highlighted">' + string + '</span>'))

app = angular.module('scopePicker')
app.directive('sScopePicker', ['scopePickerService', '$q', scopePicker])
app.filter('highlight', ['$sce', highlightFilter])