Page 58 - AngularJS权威教程
P. 58

38  第 7 章  过滤器


                 如果用户试图在有非法输入的情况下提交表单,我们现在可以捕获到这个行为并展示合适的
             错误信息。
                 在线示例:http://jsbin.com/ePomUnI/6/edit。

                   在失焦后显示验证信息
                 如果想保留实时错误提示的体验,可以在用户从某个输入字段失焦后提示错误信息(例如用
             户已经不在某个特定的输入字段中时)。为了实现这个效果,需要实现一个不是很复杂的指令,
             并向表单中添加一个新的变量。
                 我们需要使用的指令是ngFocus,它是这样的:

                 app.directive('ngFocus', [function() {
                     var FOCUS_CLASS = "ng-focused";
                     return {
                         restrict: 'A',
                         require: 'ngModel',
                         link: function(scope, element, attrs, ctrl) {
                             ctrl.$focused = false;
                             element.bind('focus', function(evt) {
                                 element.addClass(FOCUS_CLASS);
                                 scope.$apply(function() {
                                     ctrl.$focused = true;
                                 });
                             }).bind('blur', function(evt) {
                                 element.removeClass(FOCUS_CLASS);
                                 scope.$apply(function() {
                                     ctrl.$focused = false;
                                 });
                             });
                         }
                     };
                 }]);
                 将ngFocus指令添加到input元素上就可以使用这个指令,如下所示:

                 <input ng-class="{error: signup_form.name.$dirty && signup_form.name.$invalid}"
                     type="text"
                     placeholder="Name"
                     name="name"
                     ng-model="signup.name"
                     ng-minlength="3"
                     ng-maxlength="20" required ng-focus />
                 ngFocus指令给表单输入字段的blur和focus添加了对应的行为,添加了一个名为ng-focus
             ed的类,并将$focused的值设置为true。接下来,可以根据表单是否具有焦点来展示独立的错
             误信息。如下所示:

                 <div class="error"
                     ng-show="signup_form.name.$dirty && signup_form.name.$invalid && !signup_form.name.$focused">
                 在线示例:http://jsbin.com/ePomUnI/7/edit。

                 也可以在ngModel控制器中使用$isEmpty()方法来判断输入字段是否为空。当输入字段为空
             这个方法会返回true,反之如果不为空则返回false。
   53   54   55   56   57   58   59   60   61   62   63