1

I have an array of json objects like this:

$scope.data = [{ name: "something something", date: 982528 }, 
               { x: 1, y: { sub: 2}, prop1: "some string" }, 
               { a: "b", c: "d", e: "some string" }];

and I'm trying to filter it with:

var filteredData = $filter('filter')($scope.data, "some string");

this way in all the properties of the objectes in the array, angular compares with the search string,

in this example it will return the las two objects,

now, what i need is to pass an array of properties like:

var exclude =  ['prop1'];

so the filter will omit to compare those properties in each object, is there an angular filter with this option?

2
  • you can't exclude properties, but you can pass an object which defines which properties you are trying to include; i.e. $filter('filter')($scope.data, {e: "some string"}); would only return objects where e === "some string", but would not match this for other properties. see docs.angularjs.org/api/ng/filter/filter Commented Mar 21, 2018 at 23:48
  • @Claies mmm the problem is those json objects are biiiiiiig, at least 50 properties each, and i only need to exclude like 4 at best... Commented Mar 22, 2018 at 1:42

1 Answer 1

2

Unfortunately, you should create custom excludeFilter:

angular.module('app', []).controller('ctrl', function($scope){
  $scope.data = [
    { name: "something something", date: 982528 }, 
    { x: 1, y: { sub: 2}, prop1: "some string", prop2: "some string" }, 
    { a: "b", c: "d", e: "some string" }
  ];  
  $scope.search = 'some';
  $scope.exclude = ['prop1', 'prop2'];
}).filter('excludeFilter', function(){
  return function(data, search, exclude){
    if(!search)
      return data;
    return data.filter(function(x){
      for(var prop in x)
        if(exclude.indexOf(prop) == -1){           
           var value = x[prop];
           if(value.indexOf && value.indexOf(search) != -1)
              return true;
           if(!value.indexOf && value == search)
              return true;
        }          
      return false;
    });
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  search: <input type='text' ng-model='search'/>  
  <br>
  exclude: <input type='text' ng-model='exclude' ng-list/>    
  <ul>
    <li ng-repeat='x in data | excludeFilter : search : exclude'>{{x | json}}</li>
  </ul>
</div>

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.