In Ionic, how can you catch an event on a text input field when its value changes?
The input field:
<input type="search" placeholder="Search" ng-text-change="searchMenu()">
The controller:
// ...
$scope.searchMenu = function () {
alert('changed')
console.log(1);
};
// ...
Nothing happens when typing into the text field.
Insert <ion-input autofocus="true"></ion-input> to your HTML page. Execute ionic serve in Ionic CLI. Wait for browser to pop up with app and observe behavior.
By using [(ngModel)]="value" you bind the value variable to that input field. That way it is always updated. If you change it in the UI, it is immediately updated "in the code". And when you update it in your code, it automatically updates in the UI.
(ionChange) : This event fires only when user change value of input field. if user copy and paste same value it will not get fired. but if user enters different value then it will fire.
Ionic is Angular in a nutshell, and angular has two general ways of watching for changes:
$scope.$watch
:markup:
<input type="search" placeholder="Search" ng-model="search" />
and code:
$scope.$watch('search',function (oldValue, newValue) {
alert('changed')
console.log(1)
});
For the sake of completeness there are also $watchGroup
and $watchCollection
ng-change
directive togher with ng-model
:markup:
<input type="search" placeholder="Search"
ng-model="search"
ng-change="onSearchChange()" />
and code:
$scope.onSearchChange = function () {
alert('changed')
console.log(1)
}
There are also advanced ways of getting changes, like creating directive that is talking to ngModel directive controller and/or creating custom formatter and parser to work with ng-model.
You need to add an ng-model
attribute and use ng-change
instead of ng-text-change
.
ng-change
is a built-in angular directive which fires events when the binded model (ng-model
) changes. ngChange documenation
So your html would be like:
<input ng-model="inputValue" ng-change="searchMenu" type="search" placeholder="Search">
In your controller, you need to add a $scope variable like:
$scope.inputValue = ''
It's ng-change not ng-text-change and you must have ng-model on that input element to trigger ng-change event
docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With