Chris Paterson
Chris Paterson

Reputation: 1149

How do I clear an input field after submitting a form?

This is one of those angular things that is unnecessarily difficult. I just want to clear an input field after submitting a form. How do I do this? I have tried the code below, but it doesn't work.

<form name="myForm" ng-submit="submitForm()">
    <input type="text" name="myField" ng-model="myField">
    <button type="submit">Submit</button>
<form> 

$scope.submitForm = function(){
    $scope.myField.$setPristine(); // doesn't work
    $scope.myField.$setPristine(true); // doesn't work
    $scope.myField = ''; // doesn't work
};

What am I doing wrong?

Upvotes: 1

Views: 7386

Answers (3)

Sm03leBr00t
Sm03leBr00t

Reputation: 1

I just did this and it worked

    $scope.submitForm = function(){
    $scope.myField = ''; 
  };

Upvotes: 0

Victor Soto
Victor Soto

Reputation: 234

Here's a plunker I created..

http://plnkr.co/edit/NdS5rUJ8uAqb8mhBsOBr?p=preview

What is did was pass the ng-model on the ng-submit and add a field on your myField scope to properly form the generated model.

Upvotes: 1

Brocco
Brocco

Reputation: 65053

The issue is that you are getting an error on these lines:

$scope.myField.$setPristine(); // doesn't work
$scope.myField.$setPristine(true); // doesn't work

to correct this use this:

$scope.myForm.myField.$setPristine();
$scope.myForm.myField.$setPristine(true);
$scope.myField = '';

In order to reference items on the form, you must first reference the form.

Here is a working fiddle showing this example

Upvotes: 4

Related Questions