如何在以下代码中在 AngularJS 中成功提交后清空(或重置)表单上的所有输入字段

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

本文关键字:表单 输入 字段 清空 代码 AngularJS 成功 提交      更新时间:2023-09-26

我有以下控制器代码:

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);                   
            });             
        }
    }]);

所有 HTML 字段都是输入字段,可以使用$scope对象进行访问。

我尝试了$setPristine但没有用。

有人请帮助我将仅在我的代码中成功提交表单后将所有字段设置为空。

谢谢。

如果您想

在完成后重置表单,我认为您必须在解决post请求后手动重置$scope.manageUsers对象:

  $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);
  });

你可以在这里使用$setPristine()

$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演示在行动。

它应该适合你。

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