2013-12-11 16 views
5

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を取り除く方法ではありませんか?

+0

ドキュメント(http://docs.angularjs.org/api/ng.$sce)ディレクティブに '$ sce'を使用する例を挙げてください。フィルタの外でそれを使うことができるようにしなければなりません。 – tennisgent

+0

(trustAsHtml)は指示文で動作しています(http://jsfiddle.net/isnigirev/c2wRq/5/) 。誤って同じ "ラベル"でtrustAsHtmlを2回呼び出すと、エラー:[$ sce:itype]が文字列を必要とするコンテンツの文字列以外の値を信頼しようとした:Context:html "エラーが発生しました。 – ivsn

+0

質問の第2部分はまだ残っていますが、いくつかの回避策で解決します。とにかく、それも解決するのは面白いです。 – ivsn

答えて

11

hereで作業しています(trustAsHtml)。 "Error: [$sce:itype] Attempted to trust a non-string value in a content requiring a string: Context: html"エラーが発生しました。誤って同じ「ラベル」でtrustAsHtmlを2回呼び出すとエラーが発生しました。

質問の残りの部分はまだ残っていますが、いくつかの回避策で解決します。とにかく、それも解決するのは面白いです。

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); 
     }; 
    }]); 
+1

このコードを使用すると、エラーが表示されます。**エラー:$ sce:itype SCEトラストコールに文字列値が必要です**解決方法は? – Ahmed

+0

少し遅れますが、 'trustAsHtml'に文字列を渡していることを確認してください - 未定義ではなく、ヌルではなく、リストではなく文字列です。 – blacklwhite

関連する問題