I am using the Angular 1.5.2, building the validations on the top of the ng-messages. Basically, that is supposed to be like this, and certainly that works.
<form name="myform" class="form-horizontal">
<h1>{{myform.name.$error}}!</h1>
<input type="text" class="form-control" name="name" ng-model="name" required maxlength="3">
<div ng-messages="myform.name.$error" role="alert">
<div ng-message="maxlength">max length</div>
<div ng-message="required">required</div>
</div>
</input>
</form>
However, I am thinking about a way to inject the validation rules and validation message dynamically, the idea is that I will create a directive (named "validate"), the directive is supposed to be add necessary attributes like "required", "maxlength", .... and also append ng-messages as well, like this
<form name="myform" class="form-horizontal">
<h1>{{myform.name.$error}}!</h1>
<input type="text" class="form-control" name="name" ng-model="name" validate />
</form>
app.directive('validate', ['$compile', function ($compile) {
return {
restrict: 'A',
replace: false,
compile: function(element, attrs) {
element.removeAttr("ng-required");
element.attr("ng-required", "true");
element.removeAttr("maxlength");
element.attr("maxlength", "3");
var validationMessages = angular.element('<div ng-messages="myform.name.$error" role="alert"><div ng-message="maxlength">max length</div><div ng-message="required">required</div></div>');
element.append(validationMessages)
}
};}]);
My directive doesn't work, I see attributes are already added, ng-messages is also appended, but the validation is not working, something I am doing wrong?
my plunker: https://plnkr.co/edit/GAd9UdcHxCDyV6dH1Q7e