Angular ngModel.$validate() 在指令中未定义



我正在尝试使用角度集成一个简单的密码验证检查。出于某种原因,无论我做什么ngModel.$validate()都没有定义,因此实际上没有发生验证。任何帮助都非常受欢迎。我有一个自定义控制器:

angular.module('todo')
    .controller('RegisterController', ['$scope', '$http', '$location', function($scope, $http, $location) {
        $scope.register = function () {
    });

我有一个路由器:

.config(function($routeProvider) {
    $routeProvider.
        when('/todo', {
            templateUrl: './partials/todo.html',
            controller: 'TodoController'
        }).
        when('/register', {
            templateUrl: './partials/register.html',
            controller: 'RegisterController'
        }).
        otherwise({
            redirectTo: '/todo'
        });
});

我有一个指令:

var compareTo = function() {
    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() {
                console.log('in otherModelValue ');
                console.log('ngModel.$validate() : ' + ngModel.$validate());
                ngModel.$validate();
            });
        }
    };
};
angular.module('todo').directive("compareTo", compareTo);

我通过以下方式将它们绑定在一起:

    <input id="password" name="password" type="password" placeholder="Password" ng-model="password" required/> <br/>
    <input id="passwordConfirm" type="password" placeholder="Repeat Password"  ng-model="confirmPassword" required compare-to="password" /> <br/>

ngModel.$validate()应该在设计上未定义,因为它不返回任何特定值。您确定您的验证不起作用,但无法显示该验证吗?尝试添加到您的模板(假设您的表单有name="form"):

<span ng-show="form.confirmPassword.$error.compareTo">Passwords must match</span>

同时将 confirmPassword name属性添加到确认密码字段

最新更新