Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS, clear input text with button

Using AngularJS, what is the proper way to clear the value of a text field? I have an input field with a button next to it. The user types in it and hits the button to clear or reset it.

I know I can add an ng-click event on the button itself and call a function, but I am not sure that is the correct way to do it.

Right now all I have is:

<input type="text" ng-model="searchQuery" />
<button class="btn" <!--do something here maybe?-->>
  <i class="icon-search" ng-class="{'icon-refresh': searchQuery.length}"></i>
</button>
like image 453
Ronnie Avatar asked Mar 09 '13 00:03

Ronnie


People also ask

How to clear textbox value on button click in AngularJS?

Just clear the scope model value on click event and it should do the trick for you. Or if you keep your controller's $scope function and clear it from there. Make sure you've set your controller correctly.

How to clear input field on button click in Angular?

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 delete a form in Angularjs?

resetForm = function(){ /* reset the data to a new object so that all the properties * of form are reset */ $scope. data = {}; }; });


2 Answers

I had the same problem. Maybe simple is best?

No need for calling a method in the controller. No need for a directive either. Just a brief statement to clear the model that you declared in the input tag. Like this:

<input ng-model="searchQuery">
<button class="btn" ng-click="searchQuery = ''"></button>

You may also hide the clear button when there is no text in the input, like this:

<button class="btn" ng-show="searchQuery.length" ...></button>

By the way, maybe a directive that would put the clear button inside of the input box would be nice. Something like you see on the iPhone.

like image 75
nijlgier Avatar answered Sep 30 '22 02:09

nijlgier


ng-click is the "Angular" way to do it

just declare a function in your scope and attach it to the button's ng-click

If you wanted something more advanced, then the "Angular way" suggests creating a directive to wrap the functionality you want in it and attach it somehow to your button (depending on how you implement your directive)

If you want an example, let me know in the comments

like image 38
Dogoku Avatar answered Sep 30 '22 01:09

Dogoku