AngularJS:为什么我的字段无效?

时间:2015-07-18 04:17:25

标签: angularjs angular-directive

我有密码的自定义验证

app.directive('userPassword', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {
            ctrl.$validators.myValidator = function(modelValue, viewValue) {
                var msg = helper.validation.user.localPassword(modelValue)
                ctrl.$error.message = msg
                ctrl.required = helper.validation.user.localPassword()
                return ! msg
            }
        }
    }
})

这是我的密码html:

<div class="my-form-group">
    <label for="signup_password">Password:</label>
    <input ng-model="password" type="password" name="password" id="signup_password" 
        placeholder="Enter Password"
        user-password ng-required="signupForm.password.required" class="my-form-control">
</div>

当我输入abcd时,指令link函数的返回值为true。当我检查元素时,我得到了这个:

class="my-form-control ng-invalid ng-dirty ng-valid-parse ng-valid-required ng-valid-my-validator ng-touched" 

如您所见,requiredmy-validator都有效(ng-valid-requiredng-valid-my-validator。为什么我的课程仍为ng-invalid

当我检查整个表单时,它是ng-valid

更新。如果我使用scope代替ctrl,那就可以了。

ctrl.$validators.myValidator = function(modelValue, viewValue) {
    var msg = helper.validation.user.localUsername(modelValue)

    scope.userUsername = {}
    scope.userUsername.message = msg
    scope.userUsername.required = helper.validation.user.localUsername()
    return ! msg
};

以HTML格式

<input ng-model="username" type="text" name="username" id="signin_username" 
       placeholder="Enter Username"
       user-username ng-required="userUsername.required" class="my-form-control">

<div ng-show="signinForm.username.$touched && userUsername.message">
    {{userUsername.message}}
</div>

但我不想污染控制器范围。如何使用ctrl代替scope

编辑: 您可以将以下样式添加到标题中。输入字段始终为红色。

http://plnkr.co/edit/deAQoIw4KfekIh3ZOt1j?p=preview

<style>

    input.ng-invalid.ng-touched {
      background-color: #FA787E;
    }

    input.ng-valid.ng-touched {
      background-color: #78FA89;
    }

    input.ng-pending.ng-touched {
      background-color: #b3933b;
    }
</style>

1 个答案:

答案 0 :(得分:1)

这是我username字段的实现。密码应该几乎相同。

                var def = $q.defer()
                ctrl.message = 'checking the server for username unique'
                restService.checkIsUsernameUnique(modelValue, function() {
                    ctrl.message = 'ok its unique username'
                    def.resolve()
                }, function(err) {
                    ctrl.message = err.message
                    def.reject()
                })
                return def.promise;

以HTML格式

            <div ng-show="form.username.$touched && form.username.message">
                {{form.username.message}}
            </div>

简而言之,如果您想要添加非错误消息,请不要在ctrl.$error内放置消息