This question has already been answered:

Good day. A question. How to make a directive on an angular for validating the comparison of the entered data (if they are equal - well, not equal - disable buttons). My option for some reason does not work ..

Js

function personalController($scope, personalService) { $scope.changePassword = function () { $scope.oldPassword; $scope.newPassword; $scope.confirmNewPassword; $scope.myCompare = function() { return angular.equals($scope.newPassword, $scope.confirmNewPassword); }; } angular.module('appPersonal').directive('equalPass', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(equalPass) { ctrl.$setValidity('equalPass', $scope.myCompare()); }); } }; }); angular.module('appPersonal') .controller('personalController', ['$scope', 'personalService',personalController]); 

html

  <input ng-model="confirmNewPassword" type="password" placeholder="confirm new password" name="confirmNewPassword" required equalPass><br> <span ng-show="recoverPassword.confirmNewPassword.$error.equalPass" class="text-danger">New password and confirm password mast be equals!</span> 

Reported as a duplicate by members of Grundy , zRrr , user194374, Nick Volynkin 9 Jun '16 at 6:17 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • myCompare is described in the Osprey, and trying to be called as a simple function - Grundy
  • why decided to use a parser, but not $ validators? - Grundy
  • added scope for myCompare. I decided to use the parser because I found a similar example in Google ... so wrong? - Aleksei
  • $scope - you have the scope parameter on $scope - Grundy

1 answer 1

One of the variations on the theme, $viewChangeListeners is used here, you can further develop the theme, a working example in codepen

 (function () { angular .module('app',[]) .controller('AppController',['$scope', function($scope){ $scope.user = {}; }]) .directive('samePassword', SamePasswordDirective); function SamePasswordDirective() { return { restrict: 'A', require: 'ngModel', link: link, scope: { samePassword: '=' } }; ////////////////// function link(scope, element, attrs, ngModel) { ngModel.$viewChangeListeners.push(function () { ngModel.$setValidity('samePassword', scope.samePassword.$modelValue === ngModel.$modelValue); scope.samePassword.$setValidity('samePassword', scope.samePassword.$modelValue === ngModel.$modelValue); }); } } })();