How do I fire an event when user types in input form?


#1

I’m trying to develop a search function that instantly filters out elements in the list that the user is seeing as he types the search terms. I’m new both to ionic and angularjs, but not new to programming or javascript (Most of what I’ve ever worked on was jQuery based).
How do I get an event to be fired on every new character the user types on the search field?

Additionally, where can I find more content about how to use events in ionic? I couldn’t find much information on events when I searched.

Regards!


#2

Hey MateusLST.

You should look at ng-change. I have created a very simple jsfiddle to get you started. Let me know if you have any questions.

jsfiddle


#3

If you specifically want to check each time the user types a character you can use a directive with keyup:

HTML:

<input type="text"
   ng-model="inputFilter"
   search-filter>

JS:

.directive('searchFilter', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            element.bind('keyup', function() {
                rawElement = element[0];
                var inputValue = rawElement.value;
            });
        }
    };
});

You can also use filter on the ng-repeat (or collection-repeat):

<div ng-repeat="item in items | filter: inputFilter">
    <span>{{item.name}}</span>
</div>

And finally, you could call a function which filters the list in the javascript by passing that filter to the function

HTML:

<div class="item location-item"
     collection-repeat="item in (items =  getFilteredItems(inputFilter))"
     collection-item-height="item.letter ? 40 : 65"
     ng-style="{'height': item.letter ? '41px' : '66px'}">
        {{ item.name }}
    </div>
</div>

JS:

function getFilteredItems(filter) {
    var collection = $scope.items;

    // Filter items 
    return collection.filter(function(item) {
        var itemDoesMatch = !filter || item.name.toLowerCase().indexOf(filter.toLowerCase()) > -1;

        return itemDoesMatch;
    });
}

I’ve removed most of the code from the examples that I didn’t find relevant so these may not be complete examples. As you can see there are multiple ways to accomplish what you need, it just depends on the complexity of your case.

Any events specific to Ionic can be found at the docs, but since Ionic is built off of Angular you will need to go to their docs to find more information on the Angular events.