Gonzalo Pincheira Arancibia Gonzalo Pincheira Arancibia - 6 months ago 28
AngularJS Question

Angular Filter by property OR another property

I've been trying to filter programatically an array using the angular filter

$filter('filter')
. I want to filter based in two properties, but i want that the result search in a property and/or another property.

Using this array

[{
id:1,
name:'User2',
rut:'22.222.222-2',
created_at:'2016-03-23T18:36:34.404Z',
updated_at:'2016-03-23T18:36:34.404Z',
role_id:1},

{
id:2,
name:'User1',
rut:'11.111.111-1',
created_at:'2016-03-23T18:36:34.416Z',
updated_at:'2016-03-23T18:36:34.416Z',
role_id:3}
];


When i search using the string "2016" i get the entire array because my filter search in all the properties, I need that if i search, looking in the properties
name
OR
rut
.

This it's my function that search:

vm.usersList = angular.copy(UsersResolve);

function search(_searchString){
vm.usersList = $filter('filter')(UsersResolve, {$: _searchString})
: UsersResolve;
}

Answer

$filter('filter')(array, expression, comparator)

The expression argument can be a function(value, index, array) {}. You can use this to filter out the array.

var searchString = '2016';
vm.usersList = $filter('filter')(UserResolve, function(value, index, array){
    if(value.name == searchString || value.rut == searchString) {
      return true;
    }    
  });

See this Plunker.