0

How can I filter one search term on different fields combining them in an OR statement?

<ul>
    <li ng-repeat="person in persons| filter:filters{surname: 'foo' OR name: 'foo'}">
        {{person}}
    </li>
</ul>
2
  • create a custom filter introducing your condition inside, you will have to pass both perso.surname and person.name docs.angularjs.org/guide/filter#creating-custom-filters , its better to not give it ready its easy try it Commented May 4, 2018 at 12:15
  • 1
    Have you tried <li ng-repeat="person in persons" ng-if="person.surname ==='foo' || person.name==='foo' "> Commented May 4, 2018 at 12:16

1 Answer 1

2

You either filter by all properties of each object with | filter:'foo', or create a custom filter, e.g.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.persons=[
    {"id":1,"name":"foo","surname":"bar"},
    {"id":2,"name":"baz","surname":"foo"},
    {"id":3,"name":"null","surname":"undefined"},
    {"id":4,"name":"name","surname":"surname"}
  ]
});
app.filter('searchBy', function() {
  return function(array, param) {
    var new_array = [];
    angular.forEach(array, function(value) {
      if (value.name == param || value.surname == param) { // your filter query in here
        new_array.push(value);
      }
    })
    return new_array;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="person in persons| searchBy:'foo'">
      {{person}}
    </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.