F
F
ForveAvar2014-11-24 18:44:28
JavaScript
ForveAvar, 2014-11-24 18:44:28

How to organize validation and model change through a directive?

Hello!
There is such a task: for input[type="number"] it is necessary to implement support for the maxlength property, but so that it works like in input[type="text"], that is, it prohibits input if it reaches the maxlength limit.
I made one option through $parsers and it works like it should, but this option does not cover the case when the data entered the directive is already incorrect. For this option, I did it through $ formatter and it also works, but something tells me that I did something stupid
, here is the directive how I did it

angular.module('dashboardApp')
  .directive('validateMaxLength', function () {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        defaultValue: '@'
      },
      link: function (scope, elem, attrs, ctrl) {
        var previousValue = scope.defaultValue;
        var maxLength = parseInt(elem.attr('maxlength'), 10);

        function updateViewValue(updateValue){
          ctrl.$setViewValue(updateValue);
          ctrl.$render();
        }

        if (!ctrl){
          return;
        }

        if (isNaN(parseInt(previousValue, 10))){
          previousValue = "1";
        }

        if (maxLength > 0 && !isNaN(maxLength)){
          ctrl.$parsers.push(function (inputValue){
            if (inputValue.length > maxLength){
              updateViewValue(previousValue);

              return previousValue;
            }
            previousValue = inputValue;

            return inputValue;
          });

          ctrl.$formatters.push(function(modelValue){
            if (modelValue.length > maxLength){
              updateViewValue(previousValue);

              return previousValue;
            }
            return modelValue;
          });
        }
      }
    };
  });

usage
<input ng-model=imageInterval" maxlength="3" type="number" validate-max-length default-value="{{defaultValue}}"></input>

How can you check and edit the model at the first initialization?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Romanov, 2014-11-25
@Serhioromano

a few things I don't understand. You have the validateMaxLength directive, which means that the attribute must be validate-max-length. But for some reason you check parseInt(elem.attr('maxlength'), 10); where is the maxlength attribute. I don't know how it works. I haven't tested it, but by eye, it shouldn't work correctly.
Didn't quite understand the question? Do you want field validation to occur on form load before data entry begins? Or do you just need to do something with the model at the time of form initialization? So what are you doing controller?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question