简体   繁体   中英

How to empty(or reset) all the input fields on a form after successfull submission in AngularJS in following code?

I've a following controller code with me :

var app = angular.module('app_name');

app.controller("manageUsersController", [ "config", "$scope", "$http", "$mdToast",
    function(config, $scope, $http, $mdToast) {

        $scope.add = function() {
            var userData = {
                email : $scope.manageUsers.email,
                password : $scope.manageUsers.password,
                schoolId : '1',
                name : $scope.manageUsers.name,
                mobileNumber : $scope.manageUsers.mobileNumber
            };
            $http.post(config.webServicesUrl.postAddUser, userData, headerConfig).success(
                    function(data) { 
                                    displayToastMessage("User added successfully", $mdToast);
                    }).error(function(error) { 
                        console.log(error.error);                   
            });             
        }
    }]);

All the HTML fields are input fields and are accessed using $scope object.

I tried with $setPristine but it didn't work.

Somebody please help me in setting all the fields to empty upon successful submission of form only in my code.

Thanks.

If you want to reset your form upon completion, I think you have to reset the $scope.manageUsers object manually once your post request has resolve:

  $http.post(config.webServicesUrl.postAddUser, userData, headerConfig).success(
    function(data) {
      // has I don't know if you have other properties
      // I reset each property manually,
      // but you could probably do $scope.manageUsers = {}
      $scope.manageUsers.email = null;
      $scope.manageUsers.password = null;
      $scope.manageUsers.name = null;
      $scope.manageUsers.mobileNumber = null;
      displayToastMessage("User added successfully", $mdToast);
    }).error(function(error) {
    console.log(error.error);
  });

You can use $setPristine() here:

$http.post(config.webServicesUrl.postAddUser, userData, headerConfig).success(
  function(data) {
    displayToastMessage("User added successfully", $mdToast);
    $scope.form.$setPristine(); // <---------here.
  }).error(function(error) {
  console.log(error.error);
});

Plnkr demo in action.

It should work for you.

 $http.post(config.webServicesUrl.postAddUser,userData,headerConfig)
               .success(function(data) { 
                  $scope.manageUsers={};                      
                  displayToastMessage("User added successfully.", $mdToast);
              }).error(function(error) { 
                  console.log(error.error);                   
             });  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM