Joren
Joren

Reputation: 9915

Clear an input field on form submit in Angular?

I've gathered that $setPristine is supposed to do this, but it isn't on my project. This is my form:

form(name="new_project", ng-submit="create_project()")
    div.create_wrapper
        input#project_name(required, ng-model="project.name", type="text")
        select#project_language(required, ng-init="project.language='PHP'", ng-model="project.language", ng-options="language for language in languages")
        input.button.tiny.radius(type="submit", value="Create")

And the js:

$scope.create_project = () ->
    project = new projectFactory this.project
    project.$save project, (form_data) ->
        $scope.projects.push form_data
        $scope.new_project.$setPristine()

There are no errors, and pristine is set to true, but the inputs value remains.

Upvotes: 10

Views: 69744

Answers (2)

Vladyslav Babenko
Vladyslav Babenko

Reputation: 1369

You can user your own method but with some improvement. For example, This is your model into controller:

    $scope.registrationForm = {
    'firstName'     : '',
    'lastName'      : ''
};

Your HTML:

<form class="form-horizontal" name="registrForm" role="form">
   <input type="text" class="form-control"
                       name="firstName"
                       id="firstName"
                       ng-model="registrationForm.firstName"
                       placeholder="First name"
                       required> First name
   <input type="text" class="form-control"
                       name="lastName"
                       id="lastName"
                       ng-model="registrationForm.lastName"
                       placeholder="Last name"
                       required> Last name
</form

Then, you should clone/save your clear state by:

$scope.originForm = angular.copy($scope.registrationForm);

Your reset function will be:

$scope.resetForm = function(){
    $scope.registrationForm = angular.copy($scope.originForm); // Assign clear state to modified form 
    $scope.registrForm.$setPristine(); // this line will update status of your form, but will not clean your data, where `registrForm` - name of form.
};

In such way you are able to clean up the whole your form

Upvotes: 0

Joren
Joren

Reputation: 9915

Gonna leave this here, since that other question is poorly named for finding the solution to this problem.

You have to manually clear the values of the form elements.

For example, if you have:

input#project_name(ng-model="project.name", type="text")

To empty it you could do:

$scope.project = null

in your controller.

Upvotes: 19

Related Questions