字段上的$ setValidity不会使表单无效

时间:2014-01-30 02:10:41

标签: angularjs

我有一个带有一个字段的简单表单(但是有了所有的东西,它变得非常复杂)。

<form class="smart-form" name="newAdminForm" ng-submit="addAdminUser()" novalidate="novalidate">
                <fieldset>
                    <legend>Add Admin User</legend>
                    <section>
                        <label class="input"
                               ng-class="{ 'state-error' : ((newAdminForm.email.$invalid && !newAdminForm.email.$pristine) || !newAdminForm.email.$error.duplicate) && submitted }">
                            <i class="fa fa-envelope-o icon-append"></i>
                            <input type="email" ng-model="newAdminEmail" name="email"
                                   required="required"
                                   ng-class="{ 'invalid' : newAdminForm.email.$invalid && !newAdminForm.email.$pristine }">
                        </label>
                        <em class="invalid" for="email" ng-show="!newAdminForm.email.$valid && submitted">
                            Please enter valid email address.
                        </em>
                        <em class="invalid" for="email" ng-show="!newAdminForm.email.$error.duplicate && submitted">
                            User with this email is already an admin for this company profile.
                        </em>
                        <div class="note">
                            <i class="fa-fw fa fa-info"></i>
                            Enter the email address of a person you would like to add as
                            an admin of your business profile. We will notify them with a message and allow them to set
                            their password.
                        </div>
                    </section>
                </fieldset>
                <footer>
                    <button type="submit" class="btn btn-primary">Add Admin</button>
                </footer>
            </form>

ng-submit启动此功能:

$scope.addAdminUser = function(){
        $scope.submitted=true;
        if($filter('filter')($scope.admins, {'email' : $scope.newAdminForm.email}).length > 0){
            $scope.newAdminForm.email.$setValidity("duplicate", false);
        }

        if($scope.newAdminForm.$valid){
            // we'll add the user
            console.log('form still valid?');
        }
    };

电子邮件的有效性设置为false,屏幕上显示相应的错误消息。但表格本身仍然有效!我错过了什么?

1 个答案:

答案 0 :(得分:2)

原因是您的$ setValidity未被调用。你传递了错误的参数来过滤。尝试:

if($filter('filter')($scope.admins, {'email' : $scope.newAdminForm.email.$modelValue}).length > 0){
        $scope.newAdminForm.email.$setValidity("duplicate", false);
}

注意$scope.newAdminForm.email.$modelValue

DEMO

或直接使用您的模型属性newAdminEmail

if($filter('filter')($scope.admins, {'email' : $scope.newAdminEmail}).length > 0){
        $scope.newAdminForm.email.$setValidity("duplicate", false);
}

DEMO