David Anthony Acosta David Anthony Acosta - 1 year ago 109
AngularJS Question

AngularJS Custom Directive - Match More Than One Field?

I have a custom directive obtained from https://github.com/neoziro/angular-match that matches two form fields. However, how can I customize it to match more than one field? Here is better explanation of what I mean:

-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.)

Currently, I can only match it up to one field.

HTML Form:

<input type="text"
<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);

Answer Source

It might be easier to write your own directive for this, especially since angular-match plugin is no longer maintained.

To watch multiple form inputs, just pass the ng-model of each desired input to the directive. Here I called it 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]}}"/>

Now for the directive

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.

Here is a fiddle showing validation of form inputs: https://jsfiddle.net/cpgoette/und9t5ee/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download