Angular JS filter logical AND using a few terms

I have a text box in my html and I would like to filter the results on my page with logical AND from the terms that I entered in the box. Let me demonstrate

Suppose my page has

- Example number 1
- Example number 2
- Example number 3

Usually, if I want to filter the results, I will do something like

<input type= "text" ng-model= "query">

And later

<tr ng-repeat= "thing in blah | filter : query">
    <td> {{thing}} </td>
</tr>

So, if I typed

"Example"

I would understandably not "filter" anything. However, how would I make a logical AND, with a few search terms? For example, if I type

"Example 1"

, "", "1". angular, , , , , , - .

+4
3

:

filter('and', function($log) {
  return function(items, query) {
    if (!query) return items; // return all items if nothing in query box

    var terms = query.split(' '); //split query terms by space character
    var arrayToReturn = [];

    items.forEach(function(item){ // iterate through array of items
      var passTest = true;
      terms.forEach(function(term){ // iterate through terms found in query box
        // if any terms aren't found, passTest is set to and remains false
        passTest = passTest && (item.toLowerCase().indexOf(term.toLowerCase()) > -1); 
      });
      // Add item to return array only if passTest is true -- all search terms were found in item
      if (passTest) { arrayToReturn.push(item); }
    });

    return arrayToReturn;
  }
})

filter: query:

<tr ng-repeat="thing in blah | and:query">

-

+4

. Angulars 3 :

  • ( )

:

  app.filter('multiple', ['filterFilter', function (filterFilter) {
    return function (items, query) {
      if (!query) return items;

      var terms = query.split(/\s+/);
      var result = items;
      terms.forEach(function (term) {
        result = filterFilter(result,term);
      });

      return result;
    }
  }]);
+2

Mark's accepted answer also helped me, but when using objects, not strings, you need to use dot notation to access specific values. (e.g. "name" and "name")

items.forEach(function(item){ // iterate through array of items
    var passTest = true;
    var found = false;
    terms.forEach(function(term){ // iterate through terms found in query box
        // if any terms aren't found, passTest is set to and remains false
        found = (item.name.toLowerCase().indexOf(term.toLowerCase()) > -1)
            || (item.title.toLowerCase().indexOf(term.toLowerCase()) > -1); 
        passTest = passTest && found;
    });
    // Add item to return array only if passTest is true -- all search terms were found in item
    if (passTest) { arrayToReturn.push(item); }
});
0
source

Source: https://habr.com/ru/post/1539493/


All Articles