exact filter in angular

前端 未结 6 1363
天命终不由人
天命终不由人 2020-11-29 12:10

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

Example:

var words = [
    {   title: \"ball\"   },
    {            


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 12:54

    UPDATE

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

    Find words that exactly match title: 
    
    
    and exactly match type:
    {{word.title}}

    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;
      }
    });
    
    
    
      Find words that exactly match title: 
      
      
    and exactly match type:
    {{word.title}}

    PLUNKER

提交回复
热议问题