Showing posts with label Knockout js arrayFilter. Show all posts
Showing posts with label Knockout js arrayFilter. Show all posts

Wednesday, 26 February 2014

Knockoutjs array filter

arrayFilter

In arrayFilter, search items from existing array collection. If items are matched then returns true else returns false.

filterTxt = ko.observableArray([]);
Here filterTxt is observable array which bind with input field. i.e.

HTML :

<input id="filterText" data-bind="value: SearchText, valueUpdate: 'afterkeyup' />
<div data-bind="foreach: arrayFilter ">
   <p data-bind="text: Label"></p>
   <p data-bind="text: Description"></p>
</div>


SCRIPT :

var arrayFilter = ko.computed(function () {
           try {
               var text = filterTxt.toLowerCase();         
               if (!text) {
                   return arrayCollection();
               }
               else {
                   if (arrayCollection().length > 0) {
                       return ko.utils.arrayFilter(arrayCollection (), function (item) {
                           if (item.Label.toLowerCase().indexOf(text) > -1 || item. Description.toLowerCase().indexOf(text) > -1) {
                               return true;
                           }
                           else {
                              return false;
                           }
                       });
                   }
               }
           }
           catch (ex) {
               //TODO: as per need.
           }

 });