2014-06-17 59 views
2

馬克向上返回的HTML:顯示輸出,它包含可從過濾功能

<div class="vpScoreInner" ng-bind-html="reason | truncate:limit:20:" ..."> 

JS:

filter('truncate', function($sce){ 
      return function(text, overall_limit, line_limit, end){ 
       if (!text){ 
        return; 
       } 
       var last_blank_index = 0; 
       var line_length = 0; 
       var overall_length = 0; 
       var processed = ''; 
       var componenets = text.split(' '); 
       for (var i = 0; i < componenets.length; i++){ 
        c = componenets[i]; 
        if (overall_limit && overall_length + c.length >= overall_limit){ 
         return $sce.trustAsHtml(processed + end); 
        } 

        if(line_length < line_limit){ 
         processed = !!processed ? processed + ' ' + c : c; 
         line_length = line_length + c.length; 
        } 
        else{ 
         processed = processed + '<br>' 
         line_length = 0 
        } 
        overall_length = overall_length + c.length; 
       } 

       return $sce.trustAsHtml(processed); 
      } 
     }); 

這個過濾器我實現了在需要時都截斷文本,並分割它在不超過x個字符的行中沒有在中間切割詞。

問題是,與正常的ng綁定
標記呈現爲純文本,並使用相對較新的ng-bind-html,文本根本不呈現。

+0

你在這裏嘗試了答案:http://stackoverflow.com/questions/ 14726938/angular-sanitize-ng-bind-html-not-working –

回答

1

我不認爲你需要在這裏使用$sce,你的過濾器返回的值直接返回到ngBindHtml指令,而這個指令又會爲你清理和呈現HTML。

如果你看一下AngularJS文檔(https://docs.angularjs.org/api/ng/service/ $ SCE)爲$sce.trustAsHTML它返回一個需要傳遞給$sce.getTrustedHTML

Returns 

An object that can be passed to $sce.getTrustedHtml(value) to obtain 
the original value. (privileged directives only accept expressions that 
are either literal constants or are the return value of $sce.trustAs.) 

一個對象,我認爲你只需要返回創建直線上升HTML字符串並讓ngBindHTML做其餘的。

編輯:這裏有一個過濾器的一個簡單的小提琴是砍下了一個字符串轉換成大小相等,然後插入雙斷:http://jsfiddle.net/mikeeconroy/LfvZf/

+1

使用ng-bind-html是正確的,但ngSanitize也必須添加到模塊中。 –