I am creating a directive that adds a template with text type input to the view. In this directive, I am trying to add the span class for error notification if the text field input is more than max length setting provided. I have a code something like this:
<div ng-app="app">
<form name="userForm" ng-submit="processForm()" novalidate>
<div use-text-box name="xyz" ng-maxlength="10" required> </div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
My Directive like this:
var app = angular.module('app', []);
app.directive('useTextBox', function() {
return {
replace:true,
compile: function(element,attrs) {
var name = attrs.name;
var maxLengthError = attrs.hasOwnProperty('ngMaxlength') ? '<span ng-show="userForm.' + attrs.name + '.$error.maxlength" class="help-block">Text is too long. The limit is ' + attrs.ngMaxlength + ' characters.</span>' : '';
var htmlText = '<input type="text" name="' + name + '" ng-maxlength="' + attrs.ngMaxlength + '" required />' +
maxLengthError;
element.replaceWith(htmlText);
}
};
});
But in the above code, the directive is generating the input text field etc.. without a problem. However, it is not showing the error message if the max length is more than 10. What am I doing wrong?
Here is the link to the jsfiddle for the above example: http://jsfiddle.net/fB45J/3/
invalidError is not defined. did you test it?invalidErrorbefore and I forgot to delete that fromhtmlTextwhen I removed it. I have updated jsfiddle now. But that wasnt the reason why the error validation is not showing. I havent figured out why the validation aint working yet.element.replaceWithorelement.htmlyou need to compile it first with$compileand the correct scope. Second, there's no need to use the directive's compile property and the compile property should return an object with two function for pre and post directive linking.