私はその力を発見するためにAngularJSをいじっていますが、ドキュメントがあまり開発されていないことを認めなければならないので、ネストされたディレクティブで直面している問題についてここでコミュニティに尋ねています.
私は、完成した解決策よりも、理由 (および私が間違っていることの説明) を探しています。
だからここにあります(私は角度メッセージを使用していますが、問題はどのディレクティブにも共通するので重要ではないと思います):
エラー管理をすばやく変更するために、マネージャー (ここでは角度メッセージ) をディレクティブにカプセル化することにしました。フォームにエラーを表示するには、次のようにします。
<script type="text/ng-template" id="default-error-messages">
<error-message data-error="email" data-message="This field is not a valid email"></error-message>
<error-message data-error="required" data-message="This field is required"></error-message>
<error-message data-error="minlength" data-message="This field is too short"></error-message>
</script>
<form data-ng-submit="submitForm(registrationForm)" method="POST" name="registrationForm" novalidate>
<input type="email" name="email" data-ng-model="user.email" required>
<error-container data-watch-error-on="registrationForm.email.$error" data-default-errors="default-error-messages" data-ng-if="registrationForm.email.$dirty">
<error-message data-error="required" data-message="test"></error-message>
</error-container>
<button type="submit" data-ng-disabled="registrationForm.$invalid">Register</button>
</form>
directives.directive('errorContainer', ['$compile',function($compile){
return{
restrict: 'E',
transclude: true,
replace: false,
scope: {
watchErrorOn: '@'
},
template: '<div class="error-container" data-ng-transclude></div>',
compile: function(tElt, tAttrs, ctrl) {
return {
pre: function(scope, iElement, iAttrs){
iElement.find('.error-container').attr("data-ng-messages", scope.watchErrorOn);
},
post: function(scope, iElement, iAttrs){
if (angular.isDefined(iAttrs.defaultErrors)) {
var errorList = angular.element("<div data-ng-messages-include='" + (iAttrs.defaultErrors || 'default-error-messages') + "'></div>");
iElement.find('.error-container').append(errorList);
$compile(iElement)(scope);
}
}
}
},
link: function(scope, element, attrs, ctrl){
$compile(element)(scope);
}
}
}]);
directives.directive('errorMessage', ['$compile', function($compile){
return{
restrict: 'E',
template: '<div class="error"></div>',
replace: true,
scope:{
message:'@',
error:'@'
},
compile: function(tElt, tAttrs, ctrl){
return{
pre: function(scope, iElement, iAttrs){
iElement.attr('data-ng-message', scope.error);
iElement.text(scope.message);
}
}
}
}
}]);
ご承知のとおり、テンプレートにはデフォルトのエラーは一切含まれていません。プリ/ポスト コンパイル関数とリンクで多くの組み合わせを試しましたが、何も成功しませんでした。これはコンパイルの優先度の問題だと思います。おそらく ng-messages-include を最後にコンパイルする必要がありますが、その方法についてはわかりません。よろしくお願いします