onsa
2/20/2017 - 9:52 AM

Directive to check equality of two inputs (e.g. 'password' & 'confirm password') <input data-ng-model="password" ... /> <input data-ng-model

Directive to check equality of two inputs (e.g. 'password' & 'confirm password') <input data-ng-model="password" ... /> <input data-ng-model="confirmPassword" data-equals="password" ... />

'use strict';

angular.module('appName').directive('equals', ['$parse', function match($parse) {
	return {
		require: 'ngModel',
		restrict: 'A',
		link: function(scope, element, attributes, controller) {

			//	give up if no controller or empty equals attribute found
			if (!controller || !attributes.equals) {
				return;
			}

			//	get variable to be watched for change
			function getMatchValue() {
				//	parse scope for a property value = value of attribute 'equals'
				var match = $parse(attributes.equals)(scope);
				return match;
			}

			//  validate also when match value changes
			scope.$watch(getMatchValue, function() {
				controller.$$parseAndValidate();
			});

			//	add validator
			controller.$validators.equals = function(value) {
				var valid = value === getMatchValue();
				return valid;
			};

		}
	};
}]);