2013-10-11 60 views
1

我是AngularJS的新手。我正在嘗試實施一些驗證。作爲測試,我正在查看基本的登錄屏幕。該登錄屏幕的代碼如下所示:在AngularJS中驗證

<style type="text/css"> 
    input.ng-invalid.ng-dirty { background-color: red; color:white; } 
</style> 

<form novalidate name="loginForm" role="form"> 
    <div ng-show="(isDataValid==false)" class="ng-hide"> 
    Please correct the errors on the page. 
    </div> 

    <div> 
    <label for="username">Username</label> 
    <input type="text" id="username" placeholder="Username" ng-model="username" 
      required> 
    </div> 

    <div> 
    <label for="password">Password</label> 
    <input type="password" id="password" placeholder="Password" ng-model="password" 
      required> 
    </div> 

    <button type="submit" ng-click="formSubmit(loginForm);">Submit</button> 
</form> 

<script type="text/javascript"> 
    function loginController($scope) { 
    $scope.isDataValid = null; 

    $scope.formSubmit = function(f) { 
     $scope.isDataValid = f.$valid; 
     if (f.$invalid) { 
     return; 
     } 

     return false; 
    }; 
    } 
</script> 

頁面加載時,我希望它是在一個乾淨的尋找狀態(這工作)。我想在用戶開始使用字段之後進行字段級別驗證(此工作)。我想在用戶點擊「提交」時進行字段級驗證。這部分工作。

我的問題是,如果我按'提交'而不使用字段,字段上的css類不會得到更新。我相信原因是因爲這些田地不是'骯髒'的。然而,我不確定如何解決這個問題,1)滿足我的第一個要求,2)堅持讓AngularJS控制遠離DOM。

有誰知道我該怎麼做?

非常感謝!

+0

這將幫助你http://jsfiddle.net/thomporter/ANxmv/2/ – Chandermani

+0

禁用,直到形式提交按鈕是'$ dirty'和領域是'$ valid' –

回答

1

我對你的帖子發表了評論,但我想我應該舉個例子。

<button type="button" class="btn btn-primary btn-lg" ng-click="submit()" ng-disabled="(createContacts.$dirty && createContacts.$invalid) || createContacts.$pristine"><span class="icon-save"></span> Save Contacts</button> 

這是一個「提交」按鈕,我在一個名爲「createContacts」的表單中使用。當表單處於「原始」狀態(沒有輸入任何內容)和表單爲「髒」和「無效」(已輸入信息但表單有驗證錯誤)時,用戶無法使用此按鈕。

http://jsfiddle.net/Ddb4M/