Skip to content

Instantly share code, notes, and snippets.

@SapioBeasley
Last active August 6, 2017 17:26
Show Gist options
  • Select an option

  • Save SapioBeasley/ae5a508e0978055649924a79cae9a962 to your computer and use it in GitHub Desktop.

Select an option

Save SapioBeasley/ae5a508e0978055649924a79cae9a962 to your computer and use it in GitHub Desktop.
Extend ngMessages

Creating a registration form earlier today and realized angular did not come packaged with password confirm directives for ngMessages. So I needed to create one.

First things first, attach your new directive into your module.

// Creating a new directive
(function ()
{
  'use strict';
  
  angular
    .module('app.register')
    .directive("compareTo", compareTo);
})();

Within your function you will now need to define your compareTo function to handle your password and password confirm comparison.

// Logic for new compareTo directive
function compareTo()
{
  return {
    require: "ngModel",
    scope: {
      otherModelValue: "=compareTo"
    },
    link: function(scope, element, attributes, ngModel) {

      ngModel.$validators.compareTo = function(modelValue) {
        return modelValue == scope.otherModelValue;
      };

      scope.$watch("otherModelValue", function() {
        ngModel.$validate();
      });
    }
  };
}

Now in the html we can use the new compareTo directive inside the input and pass the data into your function to compare passwords.

<!-- Initial Password Input -->
<md-input-container class="md-block" md-no-float>
  <input type="password" name="password" ng-model="vm.password" placeholder="Password" required>
  <div ng-messages="registerForm.password.$error" role="alert">
    <div ng-message="required">
      <span>Password field is required</span>
    </div>
  </div>
</md-input-container>

Lastly within ngMessages, we can confirm the password using the compare-to directive, and check the validation of the compareTo with ng-message="compareTo". Input will now not allow mismatch passwords and either show an error or accept the input and submit their data.

<md-input-container class="md-block" md-no-float>
  <input type="password" name="passwordConfirm" ng-model="vm.passwordConfirm"
    compare-to="vm.password"
    placeholder="Password (Confirm)"
    required>
  <div ng-messages="registerForm.passwordConfirm.$error" role="alert">
    <div ng-message="required">
      <span>Password (Confirm) field is required</span>
    </div>
    <div ng-message="compareTo">
      <span>Passwords must match</span>
    </div>
  </div>
</md-input-container>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment