Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear an input field on form submit in Angular?

Tags:

angularjs

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.

like image 295
Joren Avatar asked Dec 27 '13 23:12

Joren


People also ask

How do you clear the input field value in angular after submit?

If you are using [(ngModel)] directive to control your form input fields, then you can clear it by setting an empty string ( ' ' ) to the ngModel control property.

How do you clear the input on a submit?

To clear an input field after submitting: When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.

How do you clear a form in angular 8?

In a model-driven form to reset the form we just need to call the function reset() on our myform model.


1 Answers

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.

like image 94
Joren Avatar answered Oct 16 '22 03:10

Joren