Skip to content

Instantly share code, notes, and snippets.

@passalini
Created July 14, 2014 19:51
Show Gist options
  • Select an option

  • Save passalini/5bfd8190443d22b9c29f to your computer and use it in GitHub Desktop.

Select an option

Save passalini/5bfd8190443d22b9c29f to your computer and use it in GitHub Desktop.

Revisions

  1. passalini created this gist Jul 14, 2014.
    28 changes: 28 additions & 0 deletions directive.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    .directive('equals', function() {
    return {
    restrict: 'A', // only activate on element attribute
    require: '?ngModel', // get a hold of NgModelController
    link: function(scope, elem, attrs, ngModel) {
    if(!ngModel) return; // do nothing if no ng-model

    // watch own value and re-validate on change
    scope.$watch(attrs.ngModel, function() {
    validate();
    });

    // observe the other value and re-validate on change
    attrs.$observe('equals', function (val) {
    validate();
    });

    var validate = function() {
    // values
    var val1 = ngModel.$viewValue;
    var val2 = attrs.equals;

    // set validity
    ngModel.$setValidity('equals', val1 === val2);
    };
    }
    }
    });
    2 changes: 2 additions & 0 deletions inputs.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    <input ng-model="user.password" />
    <input ng-model="user.confirmation" equals="{{ user.password }}" />