ng-maxlength screws up my model

后端 未结 7 894
忘掉有多难
忘掉有多难 2020-12-08 02:17

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

7条回答
  •  清歌不尽
    2020-12-08 02:52

    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:

    
    

提交回复
热议问题