1

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?

2
  • sure just create a custom filter as stated in the documentation. Commented Jun 25, 2014 at 11:41
  • Please, let me know if my solution fits! :) Commented Jun 25, 2014 at 12:58

1 Answer 1

6

Could you try this?

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

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

    filtered.sort(function(a,b){
        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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.