AngularJS无法使我的匹配(两个字段)指令工作

时间:2015-05-06 23:08:56

标签: javascript angularjs validation angularjs-directive

以下指令基于this question的代码,我使用的是Angular 1.2.27。我的问题是,无论出于何种原因,它都无法验证为真,因为它永远不会超过if (!viewValue || !comparisonModel) {,因为viewValue始终未定义。

鉴于另一个问题基本上与比较整数相同,我猜这是一个非常愚蠢的事情,我在这里错过或做错了。

那么,为什么viewValue未定义?如何让它按预期工作? 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>

1 个答案:

答案 0 :(得分:2)

这是一个小小的错字......

WA-匹配=&#34; {{密码}}&#34;

应该是:

WA-匹配=&#34; {{fields.password}}&#34;

所以html应该是:

Password2: <input name="password2" type="password" required ng-model="fields.password2" wa-match="{{fields.password}}"/>