Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exact filter in angular

In Angular, is there a way to modify the filter such that it only returns exact matches?

Example:

var words = [
    {   title: "ball"   },
    {   title: "wall"   },
    {   title: "all"    },
    {   title: "alloy"  }
];

var wordsFiltered = filter('filter')
( 
    words, 
    { 
        'title': 'all'
    } 
);  

The above will match 'ball', 'wall', 'all' and 'alloy'. But I would like it to only match 'all'. Any way to change it?

like image 667
Ben Avatar asked Aug 14 '13 21:08

Ben


2 Answers

UPDATE

Starting from AngularJS v.1.1.3 the exact filtering is provided natively:

Find words that exactly match title: 
<input ng-model="match.title" />
<br>
and exactly match type: 
<input ng-model="match.type" />
<hr>
<table>
  <tr ng-repeat="word in words | filter:match:true">
   <td>{{word.title}}</td> 
  </tr>
</table>

Plunker


Your question implies that you would want to match against multiple object properties so here's a filter that does that:

app.controller('AppController',
    [
      '$scope',
      function($scope) {
        $scope.match = {};
        $scope.words = [
          { title: "ball", type: 'object' },
          { title: "wall", type: 'object' },
          { title: "all", type: 'word' },
          { title: "alloy", type: 'material' }
        ];
        
      }
    ]
  );
  
app.filter('exact', function(){
  return function(items, match){
    var matching = [], matches, falsely = true;
    
    // Return the items unchanged if all filtering attributes are falsy
    angular.forEach(match, function(value, key){
      falsely = falsely && !value;
    });
    if(falsely){
      return items;
    }
    
    angular.forEach(items, function(item){ // e.g. { title: "ball" }
      matches = true;
      angular.forEach(match, function(value, key){ // e.g. 'all', 'title'
        if(!!value){ // do not compare if value is empty
          matches = matches && (item[key] === value);  
        }
      });
      if(matches){
        matching.push(item);  
      }
    });
    return matching;
  }
});
<body ng-controller="AppController">

  Find words that exactly match title: 
  <input ng-model="match.title" />
  <br>
  and exactly match type: 
  <input ng-model="match.type" />
  <hr>
  <table>
    <tr ng-repeat="word in words | exact:match">
     <td>{{word.title}}</td> 
    </tr>
  </table>  
</body>

PLUNKER

like image 51
Stewie Avatar answered Sep 27 '22 17:09

Stewie


Try this :

var words = [
    {   title: "ball"   },
    {   title: "wall"   },
    {   title: "all"    },
    {   title: "alloy"  }
];

var wordsFiltered = filter('filter')
( 
    words, 
    { 
        'title': 'all'
    },
    true
);
like image 38
Jamal dine Y Avatar answered Sep 27 '22 17:09

Jamal dine Y