角度验证指令无法正常工作

时间:2016-07-21 10:19:22

标签: angularjs

我正在使用自定义角度指令来显示验证。指令代码如下

angularFormsApp.directive('showErrors',['$timeout', function ($timeout) {

    return {
        restrict: 'A',
        require: '^form',
        link: function (scope, el, attrs, formCtrl) {

            // find the text box element, which has the 'name' attribute
            var inputEl = el[0].querySelector("[name]");

            // convert the native text box element to an angular element
            var inputNgEl = angular.element(inputEl);

            // get the name on the text box so we know the property to check
            // on the form controller
            var inputName = inputNgEl.attr('name');

            var helpText = angular.element(el[0].querySelector(".help-block"));

            // only apply the has-error class after the user leaves the text box
            inputNgEl.bind('blur', function () {
                el.toggleClass('has-error', formCtrl[inputName].$invalid);
                helpText.toggleClass('hide', formCtrl[inputName].$valid);
            });

            scope.$on('show-errors-event', function () {
                el.toggleClass('has-error', formCtrl[inputName].$invalid);
            });

            scope.$on('hide-errors-event', function () {
                $timeout(function () {
                    el.removeClass('has-error');
                }, 0, false);
            });


        }
    }

}]);

和Html如下

<div class="container" id="login-form">
    <a href="index.html" class="login-logo"><img src="assets/img/logo-big.png"></a>
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h2>Login Form</h2>
                </div>
                <div class="panel-body">

                    <form name="loginForm" class="form-horizontal" novalidate>
                        <div class="form-group mb-md" show-errors>
                            <div class="col-xs-12">
                                <div class="input-group">
                                    <span class="input-group-addon">
                                        <i class="ti ti-user"></i>
                                    </span>
                                    <input type="text" class="form-control" placeholder="Username" autocomplete="Off" ng-required="true" name="username" autofocus ng-model="loginUser.username">
                                </div>
                                <span class="help-block" ng-if="loginForm.username.$error.required">Username is required</span>
                            </div>
                        </div>
                        <div class="form-group mb-md" show-errors>
                            <div class="col-xs-12" >
                                <div class="input-group">
                                    <span class="input-group-addon">
                                        <i class="ti ti-key"></i>
                                    </span>
                                    <input type="password" class="form-control" placeholder="Password"
                                           name="password"
                                           ng-model="loginUser.password" autocomplete="Off"
                                           ng-required="true">
                                </div>
                                <span class="help-block" ng-if="loginForm.password.$error.required">Password is required</span>
                            </div>
                        </div>
                        <div class="form-group mb-n">
                            <div class="col-xs-12">
                                <a href="extras-forgotpassword.html" class="pull-left">Forgot password?</a>
                                <div class="checkbox-inline icheck pull-right p-n">
                                    <label for="">
                                        <input type="checkbox"></input>
                                        Remember me
                                    </label>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="panel-footer">
                    <div class="clearfix">
                        <a href="extras-registration.html" class="btn btn-default pull-left">Register</a>
                        <a href="" class="btn btn-primary pull-right" ng-click="$event.preventDefault(); SubmitLoginForm()">Login</a>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

控制器代码:

var loginController = function ($scope, $window, $routeParams, $uibModal, $location, $filter, $rootScope, DataService, SharedProperties) {

    $rootScope.bodylayout = 'focused-form animated-content';

    $scope.loginUser = {
        username: "",
        password:""
    }



    $scope.load = function () {

        //getAppointmentInfo();
    };

    $scope.SubmitLoginForm = function () {
        $scope.$broadcast('show-errors-event');

        if ($scope.loginForm.$invalid)
            return;
    }
}

angularFormsApp.controller("loginController", ["$scope", "$window", "$routeParams", "$uibModal", "$location", "$filter", "$rootScope", "DataService", "SharedProperties", loginController]);

现在当我在下面打开表单时,输入控件验证范围默认显示。当我点击“登录”按钮时,它显示为红色并且工作正常。 问题是当页面打开时默认情况下不应显示..请参见下面的图片

enter image description here

3 个答案:

答案 0 :(得分:0)

而不是这个

loginForm.password.$error.required

试试这个

(loginForm.$submitted || loginForm.username.$dirty) && loginForm.password.$error.required

答案 1 :(得分:0)

查看ng-messages directive。它相当优雅。例如:

 <form name="myForm">
  <input type="text" ng-model="field" name="myField" required minlength="5" />
  <div ng-messages="myForm.myField.$error">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">The value entered is too short</div>
  </div>
</form>

然后,您可以将其与任何表单验证结合使用。只需将验证器的错误消息放在元素$ error对象上,它们就会自动在UI中呈现。

答案 2 :(得分:0)

我最终在这里找到了问题。在我的情况下,我使用的指令的最小值是这样变化的:

<a href="#bottom">Bottom</a>
<h1 id="bottom">This is the bottom! </h1>

这意味着该表单将不会更新,我只删除了Self并正常工作。

 ngOnChanges(changes: SimpleChanges) {
     if (changes.minDate && this.control) {
      this.control.updateValueAndValidity({ onlySelf: true });
     }
   }

只要其他人做类似的事情,就把它作为面包屑。