Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic fire event on input text value changes

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.

like image 522
user2877989 Avatar asked Aug 05 '15 15:08

user2877989


People also ask

How do you autofocus input field in ionic?

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.

How do you set the value of ion-input?

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.

What is ionChange?

(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.


3 Answers

Ionic is Angular in a nutshell, and angular has two general ways of watching for changes:

  1. Use $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

  1. Using 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.

like image 189
vittore Avatar answered Sep 28 '22 10:09

vittore


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 = ''

like image 32
MHX Avatar answered Sep 28 '22 11:09

MHX


It's ng-change not ng-text-change and you must have ng-model on that input element to trigger ng-change event

docs

like image 34
Medet Tleukabiluly Avatar answered Sep 28 '22 10:09

Medet Tleukabiluly