Clear text input on click with AngularJS


How can I clear a text input on click of a button using angularJS?

Search input

The X is a seperate link, on which I would like to trigger a function.


<input type="text" class="form-control" data-ng-model="searchAll">
<a class="clear" data-ng-click="clearSearch()">X</a>
Problem courtesy of: Barney


Just clear the scope model value on click event and it should do the trick for you.

<input type="text" ng-model="searchAll" />
<a class="clear" ng-click="searchAll = null">
    <span class="glyphicon glyphicon-remove"></span>

Or if you keep your controller's $scope function and clear it from there. Make sure you've set your controller correctly.

$scope.clearSearch = function() {
    $scope.searchAll = null;
Solution courtesy of: Robert Koritnik


If you want to clean up the whole form, you can use such approach. 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"
                       placeholder="First name"
                       required> First name
   <input type="text" class="form-control"
                       placeholder="Last name"
                       required> Last name

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

Discussion courtesy of: Vladyslav Babenko

In Your Controller

$scope.clearSearch = function() {
     $scope.searchAll = '';
Discussion courtesy of: RASEL RANA

An easier and shorter way is:

 <input type="text" class="form-control" data-ng-model="searchAll">
 <a class="clear" data-ng-click="searchAll = '' ">X</a>

This has always worked for me.

Discussion courtesy of: Shivek Parmar
$scope.clearSearch = function () {
    $scope.searchAll = "";

JsFiddle of how you could do it without using inline JS.

Discussion courtesy of: Kasper Lewau

Inspired from Robert's answer, but when we use,

ng-click="searchAll = null" in the filter, it makes the model values as null and in-turn the search doesn't work with its normal functionality, so it would be better enough to use ng-click="searchAll = ''" instead

Discussion courtesy of: San Krish

Easiest way to clear/reset the text field on click is to clear/reset the scope

<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/>

In Controller

Discussion courtesy of: pradeep gowda

This recipe can be found in it's original form on Stack Over Flow.