2

The following directive is based on the code from this question, I'm using Angular 1.2.27. My problem is that for whatever reason it won't validate to true because it never makes it further than if (!viewValue || !comparisonModel) { because viewValue is always undefined.

Given the fact the other question is basically the same just with comparing integers I guess it's something pretty stupid that I'm missing or doing wrong here.

So, why is viewValue undefined and how do I get it to work as expected? Plunker is here.

'use strict';
var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.fields = {
    password: '',
    password2: ''
  };

});

app.directive('waMatch', [
    function () {
        var link = function ($scope, $element, $attrs, ctrl) {

            var validate = function (viewValue) {
                var comparisonModel = $attrs.waMatch;

                if (!viewValue || !comparisonModel) {
                    ctrl.$setValidity('waMatch', true);
                }

                ctrl.$setValidity('waMatch', (viewValue === comparisonModel));
                return viewValue;
            };

            ctrl.$parsers.unshift(validate);
            ctrl.$formatters.push(validate);

            $attrs.$observe('waMatch', function (comparisonModel) {
                return validate(ctrl.$viewValue);
            });

        };

        return {
            require: 'ngModel',
            link: link
        };
    }
]);

HTML:

  Password: <input name="password" type="password" required ng-model="fields.password" />
  <span class="error" ng-show="form.password.$error.required && !form.password.$pristine">
    Required.
  </span>

  <br />

  Password2: <input name="password2" type="password" required ng-model="fields.password2" wa-match="{{password}}"/>
  <span class="error" ng-show="form.password2.$error.waMatch">
    Passwords must match.
  </span>
Community
  • 1
  • 1
floriank
  • 25,546
  • 9
  • 42
  • 66

1 Answers1

2

It's a small typo ...

wa-match="{{password}}"

Should be:

wa-match="{{fields.password}}"

So the html should be:

Password2: <input name="password2" type="password" required ng-model="fields.password2" wa-match="{{fields.password}}"/>
o4ohel
  • 1,779
  • 13
  • 12