针对同一个验证器共享多个字段的验证状态

Share validation state for multiple fields against the same validator

我将开始声明我已经搜索了 google 和 SO,但我没有找到针对这种特定情况的答案。是的,还有其他帖子听起来一样,但更多的是基于 "MoreThan / LessThan" 心态。这根本不遵循这种心态,所以请不要将其标记为重复引用它们。

查看 Plunker Example

我试图确保用户不会输入页面上其他地方已经存在的地址。为此,我需要验证所有地址字段,因为不同的位置可能具有相同的街道地址。一旦地址被修复为不重复,我需要验证器将所有相关字段设置为有效(如果有任何无效)。目前它只将最后修改的字段设置为有效并将其余字段设置为无效。

Plunker example 演示了正在发生的事情。我尝试了许多不同的方法,例如遍历所有字段并将它们设置为 prestine 和 untouched,然后将它们设置为 dirty 和 touched 以再次触发验证,但我没有运气让这个工作。

验证者

   angular.directive('ruleFunc', ['$parse', function($parse) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function($scope, $element, $attrs, $ngModel) {
        var validatorName = $attrs.ruleName;
        var validatorFunc = $attrs.ruleFunc;

        if (!angular.isDefined(validatorName)) {
          throw Error("rule-name attribute must be defined.");
        }

        if (!angular.isDefined(validatorFunc)) {
          throw Error("rule-func attribute must be defined.");
        }

        // in real code I passing a function call with the model as the param
        // this example demonstrated the issue I am having though
        var expressionHandler = $parse(validatorFunc);

        // had to use viewChangeListener because changes to the model 
        // were not showing up correctly in the actual implementation
        $ngModel.$viewChangeListeners.push(function() {
          var valid = expressionHandler($scope);
          $ngModel.$setValidity(validatorName, valid);
        });
      });

表格

<form name="AddressForm" novalidate>
<h1>Address Form</h1>
<div style="margin:20px">
  <input id="Street" type="text" name="Street" placeholder="Street" data-ng-model="ctrl.address.street" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.Street.$error.profileHasContact}}
  <br />

  <input id="City" type="text" name="City" placeholder="City" data-ng-model="ctrl.address.city" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.City.$error.profileHasContact}}
  <br />

  <input id="State" type="text" name="State" placeholder="State" data-ng-model="ctrl.address.state" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.State.$error.profileHasContact}}
  <br />

  <input id="Zip" type="text" name="Zip" placeholder="Zip" data-ng-model="ctrl.address.zip" rule-func="ctrl.checkVal()" rule-name="profileHasContact"> {{!AddressForm.Zip.$error.profileHasContact}}
  <br />

  <div ng-if="(AddressForm.Street.$error.profileHasContact 
         || AddressForm.City.$error.profileHasContact 
         || AddressForm.State.$error.profileHasContact
         || AddressForm.Zip.$error.profileHasContact)">Address already exists in Main Contacts</div>

  <button type="submit">Submit</button>
</div>

我确实找到了一个 post,它足够接近我可以拼凑出一个解决方案。 Form validation - Required one of many in a group

这是更新后的 plunker

更新验证器

directive('ruleFunc', ['$parse', function($parse) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function($scope, $element, $attrs, $ngModel) {
        var validatorName = $attrs.ruleName;
        var validatorFunc = $attrs.ruleFunc;
        var groupName = $attrs.ruleGroup;

        if (!angular.isDefined(validatorName)) {
          throw Error("rule-name attribute must be defined.");
        }

        if (!angular.isDefined(validatorFunc)) {
          throw Error("rule-func attribute must be defined.");
        }

        if(angular.isDefined(groupName)){

          // setup place to store groups if needed
          if (!$scope.__ruleValidationGroups) {
              $scope.__ruleValidationGroups = {};
          }
          var groups = $scope.__ruleValidationGroups;

          // setip group if needed
          if(!groups[groupName]){
            groups[groupName] = {};
          }
          var group = groups[groupName];

          // assign model to group
          group[$attrs.ngModel] = {
            model: $ngModel
          }
        }

        function updateValidity(valid){
          if(angular.isDefined(groupName)){

            // set all models in group to same validity
            for(var prop in group){
              if(group.hasOwnProperty(prop)){
                group[prop].model.$setValidity(validatorName, valid);
              }
            }

          }
          else
          {
            // set this model validity if not in group
            $ngModel.$setValidity(validatorName, valid);
          }
        }

        var expressionHandler = $parse(validatorFunc);
        $ngModel.$viewChangeListeners.push(function() {
          var valid = expressionHandler($scope);
          updateValidity(valid);
        });
      }
    };
  }]);