I am playing with AngularJS to discover its power but I have to admit the documentation is not very developed, so I'm asking here the community for a problem I'm facing with nested directives.
I'm more looking for the reasonment (and explanations on what I'm doing wrong) than a finished solution.
So here is the thing (I am using angular-messages but I don't think it's important as the problem would be common to any directive):
To quickly change the errors management I have decided to encapsulate the manager (angular-messages here) into a directive, so to display my errors on a form I do it this way :
<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);
}
}
}
}
}]);
As your surely know, It doesn't work, default errors are not included at all in the template. I have try a lot of combinations on pre/post compile functions & link but nothing was successful. I think this is a problem of priority on compilation, maybe ng-messages-include should be the last to compile but no idea on how, thank you in advance