以下指令基于this question中的代码,我使用的是Angular 1.2.27。我的问题是,无论出于何种原因,它都不会验证为true,因为它永远不会比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>

最佳答案

这是一个小错字...

wa-match =“ {{password}}”

应该:

wa-match =“ {{fields.password}}”

因此,html应该是:

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

09-25 16:48