How can I force an angular validation directive to run?

前端 未结 2 780
借酒劲吻你
借酒劲吻你 2021-01-06 01:15

I\'ve created a validation directive for my form. It basically validates a fields value based on data from another field.

It works perfect :-)

My problem is

2条回答
  •  执念已碎
    2021-01-06 01:33

    It is a really bad idea to refer explicitly to some fields in your directive. As you can see, this has a lot of drawbacks : unportability, code repetition, brittleness, …

    Just make something like that :

    
    

    And :

    myApp.directive('validateGreaterInteger', function() {
        return {
        require: 'ngModel',
        scope: {
            otherInteger : '=validateGreaterInteger',
        }
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function(viewValue) {
            if (viewValue > scope.otherInteger) {
                ctrl.$setValidity('higher', true);
                return viewValue;
            } else {
                ctrl.$setValidity('higher', false);
                return undefined;
            }
        }
    });
    

    You can then simply do the typical state control (see the section "Binding to form and control state" for an exemple).

    Please notice that, in this case, you can also more simply use input[number] and its min parameter.


    Edit after the discussion in comments :

    Well, the functions in NgModelController.$parsers are obviously called only when the content of the model changes. What you want to do is to make validation whenever int1 or int2 change. So just do it :-) :

    link: function(scope, elm, attrs, ctrl) {
        scope.$watch('data', function (data) {
          if (data.int2 > data.int1) {
              ctrl.$setValidity('higher', true);
              return data.int2;
          } else {
              ctrl.$setValidity('higher', false);
              return undefined;
        }
      }, true);
    

    Use your own validation variable (int2valid in your Fiddle) is also very strange. Please use the typical state control, with something like form.int2.$error.higher.

提交回复
热议问题