AngularJS自定义指令 - 匹配多个字段?

时间:2016-08-14 14:26:37

标签: angularjs forms

我有一个从https://github.com/neoziro/angular-match获得的自定义指令,它匹配两个表单字段。但是,如何自定义它以匹配多个字段?以下是对我的意思的更好解释:

-Form Field 1
-Form Field 2
-Form Field 3
-Form Field 4

-Confirmation (I want this one to match either Field 1,2,3 OR 4.)

目前,我只能将其匹配到一个字段。

HTML表格:

<input type="text" 
       name="correctAnswer" 
       ng-model="quiz.quizData.correctAnswer" 
       match="answer1">
<div ng-show="theQuiz.correctAnswer.$error.match && !theQuiz.correctAnswer.$pristine">Answers do not match!</div>

指令:

angular.module('match', []).directive('match', ['$parse', matchDirective]);

function matchDirective($parse) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ctrl) {
      scope.$watch(function () {
        return [scope.$eval(attrs.match), ctrl.$viewValue];
      }, function (values) {
        ctrl.$setValidity('match', values[0] === values[1]);
      }, true);
    }
  };
}

1 个答案:

答案 0 :(得分:0)

为此编写自己的指令可能更容易,尤其是因为不再维护angular-match插件。

要观看多个表单输入,只需将每个所需输入的ng-model传递给指令即可。在这里我称之为match

<input type="text" name="firstNameOne" ng-model="firstNameOne"/>
<input type="text" name="firstNameTwo" ng-model="firstNameTwo"/>
<input type="text" name="firstNameThree" ng-model="firstNameThree"/>

<input type="text" name="confirmFirstName" ng-model="confirm" match="{{[firstNameOne, firstNameTwo, firstNameThree]}}"/>

现在是指令

app.directive('match', function() {
   return {
      restrict: 'A',
      controller: function($scope) {
         $scope.doValidation = function(matches) {
            //Validation logic.
         }
      },
      link: function(scope, element, attrs) {
          scope.$watch('confirm', function() {
              scope.matches = JSON.parse(attrs.match); //Parse the array.
              scope.doValidation(scope.matches); //Do your validation here.
          });
       }
    }
});

这是一个显示表单输入验证的小提琴:https://jsfiddle.net/cpgoette/und9t5ee/