Search code examples
javascriptangularjsangularjs-ng-repeatangular-filters

AngularJS filter multiple words from a string in a single field


Here the idea of my problem :

Imagine, I have an user looking for a book.

As input, he can try to find the book using book title.

Let's take :

  $scope.books = ["Heir Of Earth",
    "Woman Of The Solstice",
    "Hunters Of Next Year",
    "Pilots Without Honor",
    "Slaves And A Woman",
    "Kings And Heroes",
    "Decay Of The End",
    "Fortune Of The Land",
    "Rejecting My Dreams",
    "Painting The Angels"];

Now I take the user query in a string :

example :

$scope.userQueryTitle = "Woman Of";

I want to get all books which where their title contains "Woman" or "Of" but NOT "Woman" AND "Of".

From there, the corresponding result should be this :

$scope.booksResult = ["Heir Of Earth",
"Woman Of The Solstice",
"Hunters Of Next Year",
"Slaves And A Woman",
"Decay Of The End",
"Fortune Of The Land"
];

I found some partial solutions to my problem such as use something like :

View:

<ul ng-repeat="book in booksResult | filter: getBooksFromTitle">
    <li>{{book}}</li>
</ul>

Controller:

$scope.getBooksFromTitle = function(book){
    return book.match(($scope.userQueryTitle).split(" ")[0]) || 
        book.match(($scope.userQueryTitle).split(" ")[1]);
};

It works only if $scope.userQueryTitle contains only 2 words but my problem is what's about if I have 1 or 4 or n word(s) ?

getBooksFromTitle() should be flexible about this but I don't see how to deal with...

Any suggestion ?

Thanks !


Solution

  • Change the getBooksFromTitle function as follows,

    $scope.getBooksFromTitle = function(book){
        return $scope.books.filter(function(e){ return e.match(new RegExp($scope.query.split(" ").join('|'),'i')) });
    };
    

    Try to put as many keywords you want, this should solve your problem. Cheers