how to reset form with angular how to reset form with angular angularjs angularjs

how to reset form with angular


If you want to reset your form fields $dirty flags after a successful ajax call, then you should call setPristine() from inside of your success handler:

    $http.post('/ci_angular/api/customers/customer', customer)        .success(function() {                        $scope.customerForm.$setPristine();        });

If you want to clear your form fields, then you should initialize a model inside your controller, so that you can bind them to the view, and clear them out later:

Controller:

function CustomersController ($scope, $http) {    // initialize an empty customer.     $scope.customer = {};    // its good practice to initialize your customers array too    $scope.customers = [];    $http.get('/ci_angular/api/customers/').success(function(customers){        $scope.customers = customers;    });    $scope.addCustomer = function(customer){        $http.post('/ci_angular/api/customers/customer', customer).success(function() {            // push the customers to the array only when its successful            $scope.customers.push(customer);            // clearing the customer form is easy now, just set it to an empty object            $scope.customer = {};        });    }}var app = angular.module('app', []);app.controller('CustomersController', CustomersController);

HTML

<div ng-app="app" ng-controller="CustomersController">     <form name="customerForm">            customerName:<input type="text" name="name" ng-model="customer.name" /><br />            email: <input type="text" name="email" ng-model="customer.email" /><br />            address: <input type="text" name="address" ng-model="customer.address" /><br />            city: <input type="text" name="city" ng-model="customer.city" /><br />            state: <input type="text" name="state" ng-model="customer.state" /><br />            postalCode: <input type="text" name="postalcode" ng-model="customer.postalCode" /><br />            country: <input type="text" name="country" ng-model="customer.country" /><br />        <button ng-click="addCustomer(customer)">Add Customer</button>     </form></div>



    $scope.addCustomer = function(){      var customer = {        customerName: '',        email: '',        address: '',        city: '',        state: '',        postalCode: '',        country: '',      };

Place this code in your success function.


You can try to add a reset button on html and have reset function in $scope as below :

HTML

<button ng-click="reset()">RESET</button>

JS to add inside controller

$scope.emptyCustomers= {};$scope.reset = function() {    $scope.customers = angular.copy($scope.emptyCustomers);};

Check Angularjs docs simple form for similar example : https://docs.angularjs.org/guide/forms

Hope this helps !