Resetting form after submit in Angularjs

后端 未结 5 1151
情话喂你
情话喂你 2020-11-29 07:57

Hi I have a form which does update on button click.

 $scope.action = \"Update\";
  var id = $routeParams.editId;
  scope.item = updateRecord.get({ id: id })         


        
相关标签:
5条回答
  • 2020-11-29 08:28

    At the bottom of your submit function's body run this code below.

    // Reset the form model.
    vm.project = {};
    // Set back to pristine.
    vm.form.$setPristine();
    // Since Angular 1.3, set back to untouched state.
    vm.form.$setUntouched();
    

    "vm.form" is my form name.

    For more info have a look at this docs page: https://docs.angularjs.org/api/ng/type/form.FormController

    0 讨论(0)
  • 2020-11-29 08:33

    This worked for me.

    viewModel.data = {};
    $scope.formName.$setUntouched();
    $scope.formName.$setPristine();
    
    0 讨论(0)
  • 2020-11-29 08:33

    I dont get the question, but maybe, you can clean the form in the Html component:

    function: ngSubmit(), send the data. taskName is the name of the field, also taskBody.

    <form (ngSubmit)="onSubmit(taskName.value, taskBody.value); taskName.value=''; taskBody.value=''" #taskForm="ngForm">
    
    0 讨论(0)
  • 2020-11-29 08:41

    You can reset a form by, $scope.formName.$setPristine(); but if you're binding a model object to your inputs, you need to take care of clearing those too, ie:

    $scope.currentRecord={};

    EDIT

    As ToodoN-Mike pointed out, don't forget to set

    $scope.formName.$setUntouched()

    The $touched flag was introduced in angular 1.3.

    0 讨论(0)
  • 2020-11-29 08:43

    1) To Remove the values in Form Fields and to reset you can use $setPristine();

    $scope.formName.$setPristine();
    

    2) Next, to set the form to Untouched State too use $setUntouched();

    (If you have required fields in your form Fields and also if you are using ng-messages then if you don't use the below function those fields will show error.)

    $scope.formName.$setUntouched();
    
    0 讨论(0)
提交回复
热议问题