7

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>

2 Answers 2

30

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 - This is more the 'Angular way' just to clear the data model on click.
Great answer. Just to clarify a small typo-- double check the button searchQquery.
Thanks, I removed the second 'q'
Some would argue against having logic in the view. For one, the logic in the view can't be Unit Tested (though it can be E2E tested with protractor).
8

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

3 Comments

ok, if that is the way then I'm pretty sure I can figure it out. I wasn't sure if there was a better practice kind of way to do it. Thanks @Dogoku
and just to confirm, this is how I ended up resetting it $scope.resetSearch = function(){$scope.searchQuery = "";}
@Ronnie what if i have my ng model like this.. ng-model ="filter.to" ?? $scope.filter = '' ; -> this method never works for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.