【问题标题】:Unable to clear form fields after Submit in Angular在 Angular 中提交后无法清除表单字段
【发布时间】:2018-01-20 05:18:11
【问题描述】:

我是 Angular 的新手。我在提交后查看了很多关于清除表单字段的答案,但似乎都没有。 这是我的 HTML 代码:

  <form name="myForm" ng-submit="formSubmit()" class="form-horizontal">

      <div class="form-group">

       <input type="text" class="form-control" ng-model="user.FullName" placeholder="Full Name" required=""/>

      </div>
      <div class="form-group">
      <input type="text" class="form-control" ng-model="user.Address" placeholder="Address" required=""/>
         </div>
     <button type="submit" class="btn btn-primary" style="background-color: purple;">Submit</button>

 </form>

这是我的 JS 代码:

 var myApp = angular.module('myApp', ['ui.router']); 
 myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
   $scope.user={}
   $scope.formSubmit=function(){
     $http({
        method:'POST',
        url:'myurl',
        data:$scope.user,
        headers:{'Content-Type':'application/json'}
    }).then(function(res){
            console.log(res);
             $scope.myForm.$setPristine(); 
             $scope.myForm.$setPristine(true); 
             $scope.myForm='';      


      })
     }
  });

我尝试过 setPristine 和 setUntouched,但都没有工作。

【问题讨论】:

  • 这个问题的标签不正确。该论坛适用于 Angular 2+。请将标签更改为 angularjs
  • @RRForUI 这不是论坛,您可以提出修改建议以更改标签。

标签: html angularjs forms


【解决方案1】:

我在您的代码中没有看到奇怪的东西,我根据您的代码制作了 plnkr,我所做的修改如下。也把plnkr sample

控制器

var myApp = angular.module('myApp', ['ui.router']); 
 myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
   $scope.user={}
   $scope.formSubmit=function(){
     $http({
        method:'POST',
        url:'myurl',
        data:$scope.user,
        headers:{'Content-Type':'application/json'}
    }).then(function(res){
        $scope.myForm.$setPristine();
        $scope.user = {};
      }, function(rej){ //error});
 }
 });

【讨论】:

  • 可能对你不起作用,因为没有进入承诺的成功状态,尝试像我的 plnkr 一样将$scope.myForm.$setPristine();also 放入拒绝中。
【解决方案2】:

你应该试试

var myApp = angular.module('myApp', ['ui.router']); 
 myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
   $scope.user={}
   $scope.formSubmit=function(){
     $http({
        method:'POST',
        url:'myurl',
        data:$scope.user,
        headers:{'Content-Type':'application/json'}
    }).then(function(res){
        $scope.$broadcast('show-errors-reset');
        $scope.forms.user = {};
        $scope.forms.userFrom.$setPristine = true;
      }, function(rej){ //error});
 }
 });

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多