【问题标题】:How reset form and validation after submitting form (AngularJS)提交表单后如何重置表单和验证(AngularJS)
【发布时间】:2016-01-03 14:03:18
【问题描述】:

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

我的代码如下:

控制器:

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 中可以做到吗?谢谢!

【问题讨论】:

标签: javascript angularjs validation


【解决方案1】:

我很惊讶,但 $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

【讨论】:

  • 谢谢...我已经这样使用它了:
  • 是否可以使用$scope.myForm获取所有表单输入值?
猜你喜欢
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多