I\'m building a form with AngularJS, and I noticed some behavior I don\'t understand.
When I assign ng-minlength=5
as an input attribute, AngularJS unbi
Angular seems to return a value of undefined
when the minlength is invalid, but you can make your own validator directive:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.user = {};
$scope.user.name = "";
$scope.user.lifeStory = "";
}
myApp.directive('myMinlength', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var minlength = parseInt(attr.myMinlength); // Just for Int's sake ;)
ngModel.$parsers.unshift(function(value) {
value = value || ''; // Prevent the value from being undefined
var valid = value.length >= minlength;
ngModel.$setValidity('myMinlength', valid);
return value; // return the value no matter what
});
}
};
});
And use it like this:
Here's the updated jsfiddle
It turns out that ngRequired has the same behavior, and can be fixed in the same way. It may be like this for all the validators?
I'd also like to know why the Angular team chose to unset the property...