I\'m trying to do a simple textarea with \"so many chars remaining\" along with validation. when I use ng-maxlength to validate my form, it resets my charcount as soon as th
An alternative that I'm using is to retain the same behaviour as the ng-maxlength validator but to feed the length back via an extra attribute 'actual-length'.
app.directive('newMaxlength', function () {
return {
require: 'ngModel',
scope: {
maxlength: '=newMaxlength',
actualLength: '='
},
link: function (scope, elem, attr, ngModelCtrl) {
function validate(ctrl, validatorName, validity, value) {
ctrl.$setValidity(validatorName, validity);
return validity ? value : undefined;
}
var maxlength = parseInt(scope.maxlength, 10);
var maxLengthValidator = function (value) {
scope.actualLength = value ? value.length : 0;
return validate(ngModelCtrl, 'maxlength', ngModelCtrl.$isEmpty(value) || value.length <= maxlength, value);
};
ngModelCtrl.$parsers.push(maxLengthValidator);
ngModelCtrl.$formatters.push(maxLengthValidator);
}
};
});
Here is the element with the extra attribute: