搜尋

首頁  >  問答  >  主體

angular.js - Angular表單驗證

本人剛開始學習angular,在表單驗證這裡碰到了一些問題,我的意思是想在blur的時候再讓錯誤提示顯示出來,而在focus時不顯示錯誤信息,可是我按照書上的來打,但不正確,有誰能幫我分析下,謝謝~

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="../css/lib/bootstrap4.css">
    <script type="text/javascript" src='../js/lib/angular.js' ></script>
    <script type="text/javascript" src='js/validation2.js'></script>
</head>
<body ng-controller="myCtrl">
    <form name='signup_form' novalidate ng-submit='signupForm()'>

            <fieldset>
                <legend>Signup</legend>
            </fieldset>

            <fieldset  class="form-group">
                <label>Your name</label>
                <input type="text" class="form-control" placeholder='Name' name='name' ng-model='signup_name' ng-minlength='3' ng-maxlength='20' required ng-focus />
                
                <p class="alert alert-danger" ng-show='signup_form.name.$dirty && signup_form.name.$invalid && !signup_form.name.$focused'>
                    <small class='error' ng-show='signup_form.name.$error.required'>Your name is required</small>
                    <small calss='error' ng-show='signup_form.name.$error.minlength'>Your name is required to be at least 3 words</small>
                    <small class='error' ng-show='signup_form.name.$error.maxlength'>Your name can't be longer than 20 words</small>
                </p>
                <pre>
                    focused:{{!signup_form.name.$focused}}
                    $dirty:{{signup_form.name.$dirty}}<br>
                    $invalid:{{signup_form.name.$invalid}}<br>
                    required:{{signup_form.name.$error.required}}<br>
                    minlength:{{signup_form.name.$error.minlength}}<br>
                    maxlength:{{signup_form.name.$error.maxlength}}
                </pre>
            </fieldset>
        </form>
</body>
</html>

js

var app = angular.module('app',[]);
app.controller('myCtrl', ['$scope','$timeout', function($scope,$timeout){
    
    
}])
app.directive('ngFocus',function(){
    // var FOCUS_CLASS = "ng-focused";
    return{
        restrict : 'A',
        require : 'ngModel',
        link : function(scope,ele,attrs,ctrl){
            ctrl.$focused = false;
            ele.bind('focus',function(ev){
                // ele.addClass(FOCUS_CLASS);
                scope.$apply(function(){
                    ctrl.$focused = true;
                });
            }).bind('blur',function(ev){
                // ele.removeClass(FOCUS_CLASS);
                scope.$apply(function(){
                    ctrl.$focused = false
                })
            })
        }
    }
})
给我你的怀抱给我你的怀抱2779 天前571

全部回覆(1)我來回復

  • 某草草

    某草草2017-05-15 17:00:38

    雷雷 雷雷

    回覆
    0
  • 取消回覆