2016-05-02 10 views
1

として、私はこれに似た複数のオブジェクトの配列を、持ってNG-バインドHTMLで:NGリピート前と後のマークアップ

[ 
    { title: 'abc', 'pre': '<div class="class1"><div class="class2">', 'post': '</div>' }, 
    { title: 'def', 'pre': <div class="class3">', 'post': '</div>' }, 
    { title: 'ghi', 'pre': '<div class="class3">', 'post': '</div></div>' } 
] 

<div ng-repeat="item in myVar"> 
    <div ng-bind-html="item.pre" />{{ item.title }}<div ng-bind-html="item.post" /> 
</div> 

上記は、(私は二つのdivのを開く必要が動作しません。 1つ、そして上記の配列の2つの他の項目で閉じる)。問題は、私が使用できない要素にバインドする必要のあるNG-バインドhtmlのことではありません、どちらもフィルタの作業を行います。

<div ng-repeat="item in myVar"> 
    {{ item.pre | trust }}{{ item.title }}{{ item.post | trust }} 
</div> 

angular.module('myModule').filter('trust', ['$sce',function($sce) { 
    return function(value, type) { return $sce.trustAsHtml; } 
}]); 

任意のアイデア?

答えて

1

あなたは連結プレビューを実行し、それを信頼して(または、可能であればngSanitizeを有効にして)、注入する必要があります。

私が知る限り、あなたがしようとしている方法で部分的なHTML要素を挿入する方法はありません。お使いのコントローラで

:あなたのビューで次に

$scope.items = [...]; 

for (var i = 0; i < $scope.items.length; i++) { 
    var e = $scope.items[i]; 

    e.concatenated = $sce.trustAsHtml(e.pre + e.title + e.post); 
} 

:もちろん

<div ng-repeat="item in items"> 
    <div ng-bind-html="item.concatenated" /> 
</div> 

、あなたはおそらくたいと思うngSanitizeだけe.titleですべての問題を回避するために、オン。つまり、誰かが<script>alert('ahh!')</script>のタイトルを入力した場合、それは結局は信頼されることになります。


あなたのバージョンには、どのようにngBindHtml書かれているのに動作しませんでした:

var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) { 
    return { 
    restrict: 'A', 
    compile: function ngBindHtmlCompile(tElement, tAttrs) { 
     var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); 
     var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) { 
     return (value || '').toString(); 
     }); 
     $compile.$$addBindingClass(tElement); 

     return function ngBindHtmlLink(scope, element, attr) { 
     $compile.$$addBindingInfo(element, attr.ngBindHtml); 

     scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { 
      // we re-evaluate the expr because we want a TrustedValueHolderType 
      // for $sce, not a string 
      element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || ''); 
     }); 
     }; 
    } 
    }; 
}]; 

それは完全なHTML要素を必要とするelement.html(...)を、使用して注入します。

+0

私はng-sanitizeを使用します。コンカテインメントは本当に唯一の方法ですか? – chrney

+0

@chrneyはい、私が知る限りです。なぜか私の編集を参照してください。 *そこに回避策があるかもしれませんが、正直なところ私は連結に固執するように誘惑されるでしょう。必要に応じて、その連結を行う指示を書くことができます。 –

関連する問題