Dania Dania - 1 year ago 141
AngularJS Question

Custom search filter for AngularJs

Let suppose I have an array of strings like ["don't worry", "worry", "Always be happy and don't worry" ]

When I search for worry,using default search filter on ng-repeat, it gives me all three results irrespective of the position at which worry is in the string to be searched.

I am trying to make a custom search filter for ng-repeat such that on searching worry I should get results sorted according to the position of "worry" in the original string.

So upon searching for word "worry" in the above array, my expected output will be
["worry", "don't worry", "Always be happy and don't worry"].

Is this possible?


Could you try this?

app.filter('wordsFilter', function() {
   return function(items, word) {
    var filtered = [];

    angular.forEach(items, function(item) {
        if(item.indexOf(word) !== -1){

        if(a.indexOf(word) < b.indexOf(word)) return -1;
        else if(a.indexOf(word) > b.indexOf(word)) return 1;
        else return 0;

    return filtered;

I hope it helps!