2016-10-04 41 views
0

我試圖通過在角度過濾器上動態添加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]) 

回答

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])