How can I clear a text input on click of a button using angularJS?
The X is a seperate link, on which I would like to trigger a function.
HTML
<input type="text" class="form-control" data-ng-model="searchAll">
<a class="clear" data-ng-click="clearSearch()">X</a>
This question is related to
javascript
forms
angularjs
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"
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
Try this,
this.searchAll = element(by.xpath('path here'));
this.searchAll.sendKeys('');
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
$scope.clearfunction=function(event){
event.searchAll=null;
}
In Your Controller
$scope.clearSearch = function() {
$scope.searchAll = '';
}
$scope.clearSearch = function () {
$scope.searchAll = "";
};
JsFiddle of how you could do it without using inline JS.
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
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.
Source: Stackoverflow.com