2015-10-06 96 views
2

我想在提交表单后重置表单和所有验证消息。这里是plunker:http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview如何在提交表单后重置表单和验证(AngularJS)

我的代码是波纹管:

控制器:

app.controller('MainCtrl', function($scope) { 
    $scope.data={fullName:''}; 

    $scope.submit=function(){ 
    console.log('submit') 
    $scope.myForm.$setPristine(); 
    $scope.myForm.$setUntouched(); 
    $scope.data={fullName:''}; 
    } 
}); 

HTML:

<body ng-controller="MainCtrl"> 
<form name="myForm" novalidate> 
<div> 
    <label class="control-label">Name</label> 
    <input 
      name="full_name" 
      type="text" 
      ng-model="data.fullName" 
      ng-required="true"> 

    <p ng-if="myForm.$submitted && myForm.$invalid">Validation message</p> 
</div> 
<button ng-click="submit()" type="submit"> 
    Submit 
</button> 
</form> 
</body> 

我的问题是: 当用户在输入和点击进入名在提交按钮上,不应该显示验证消息,因为应该重新设置模型,表单和验证。我如何做到这一点?

我试图使用$ setPristine()和$ setUntouched(),但它不适用于我。

在AngularJS中可以做什么?谢谢!

+0

http://stackoverflow.com/questions/26015010/angularjs-form-reset的重复-error – DexTer

回答

2

我很高兴,但$setpristine()不更新$submitted

这可能不是最漂亮的解决方案,但似乎工作:

app.controller('MainCtrl', function($scope, $timeout) { 
    $scope.data = { 
    fullName: '' 
    }; 
    $scope.submit = function() { 
    console.log('submit') 
    $scope.data = { 
     fullName: '' 
    }; 
    $timeout(function() { 
     $scope.myForm.$setPristine(); 
     $scope.myForm.$setUntouched(); 
     $scope.myForm.$submitted = false; 
    }); 
    } 
}); 

DEMO

+0

谢谢...我已经这样使用它:

+0

是否可以使用'$ scope.myForm'获取所有表单输入值? –