2013-10-11 99 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/