1 つの DOM 要素に複数のディレクティブがあり、それらが適用される順序が重要な場合は、priority
プロパティを使用してそれらの適用を順序付けることができます。数値が大きいほど最初に実行されます。指定しない場合、デフォルトの優先度は 0 です。
編集:議論の後、ここに完全な実用的なソリューションがあります。キーは、属性を削除することでした: element.removeAttr("common-things");
、およびelement.removeAttr("data-common-things");
(ユーザーdata-common-things
がhtmlで指定した場合)
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true, //this setting is important, see explanation below
priority: 1000, //this setting is important, see explanation below
compile: function compile(element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
};
}
};
});
ワーキング プランカーはhttp://plnkr.co/edit/Q13bUt?p=previewで入手できます。
または:
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
$compile(element)(scope);
}
};
});
デモ
terminal: true
and priority: 1000
(高い数値)を設定する必要がある理由の説明:
priority
DOM の準備ができると、angular は DOM をウォークして、登録されているすべてのディレクティブを識別し、これらのディレクティブが同じ要素にあるかどうかに基づいて、ディレクティブを 1 つずつコンパイルします。カスタム ディレクティブの優先順位を高い数値に設定して、それが最初にコンパイルされるようにし、このディレクティブがコンパイルされた後terminal: true
に他のディレクティブがスキップされるようにします。
カスタム ディレクティブがコンパイルされると、ディレクティブを追加してそれ自体を削除することで要素を変更し、$compile サービスを使用してすべてのディレクティブ (スキップされたものを含む) をコンパイルします。
と を設定しないterminal:true
と、カスタム ディレクティブの前にpriority: 1000
いくつかのディレクティブがコンパイルされる可能性があります。そして、カスタム ディレクティブが $compile を使用して要素をコンパイルする場合 => 既にコンパイルされたディレクティブを再度コンパイルします。特に、カスタム ディレクティブの前にコンパイルされたディレクティブが既に DOM を変換している場合は、予期しない動作が発生します。
優先度と端末の詳細については、ディレクティブの `端末` を理解する方法は? を参照してください。
テンプレートも変更するディレクティブの例はng-repeat
(priority = 1000) で、ng-repeat
コンパイル時ng-repeat
に、他のディレクティブが適用される前にテンプレート要素のコピーを作成します。
@Izhaki のコメントのおかげで、ngRepeat
ソース コードへの参照は次のとおりです: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js