AngularJS filter (object and multiple values) not working

136 Views Asked by At

So I got a project which is using AngularJS with UI-Router, I iterate through a json which has a property called "state" which is what I want to use as a filter, however, I will be using a "selector" where I can pick "All" or a specific one.

I'm new to AngularJS So not sure exactly what is not working, this is the code I have so far:

function filterState (installment){
    switch(selectedValue) {
        case 1:
            if(installment.state === 'PAID'){
                return installment;
            }
            break;
        case 2:
            if(installment.state === 'LATE'){
                return installment;
            }
            break;
        case 3:
            if(installment.state === 'PENDING'){
                return installment;
            }
            break;
        default:
            return installment;
    }

The filter however is not working as it should Here is how I'm calling it:

<div class="row" ng-repeat="installment in vm.clients.installments | filter: filterState">

Not sure exactly what is the error, when I filter by a value manually like filter: {state:'PAID'} It works

3

There are 3 best solutions below

0
Darkly On BEST ANSWER

Apparently I needed to return a boolean value instead of the object, I did try that before, but my other issue was that I was calling the function directly instead of doing vm.function (once passed to the context), after doing that it worked.

0
xdeepakv On

Filter function returns an iterator function. like callback. Please check below example.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.criteria = { name: 'Bob'};

  $scope.criteriaMatch = function( criteria ) {
    return function( item ) {
      return item.name === criteria.name;
    };
  };

  $scope.items =[
    { name: 'Bob'},
    { name: 'Alice'}
  ];
});
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview

Credit: Anonymous

0
Bill P On

If you need to filter with a select option then you can do something like this:

<select name="select" id="select" ng-model="clients.status">
    <option value="PAID">PAID</option>
    <option value="LATE">LATE</option>
    <option value="PENDING">PENDING</option>
    <option value="ALL">ALL</option>
</select>
<div class="row" ng-repeat="installment in clients.installments | filter: filterState">
    {{installment.id}}
</div>

And in controller the function to filter:

$scope.filterState = function(installment) {
    if ($scope.clients.status === 'ALL') return true;
    return $scope.clients.status === installment.status;
};

When option ALL is selected, it shows all the items of the list

Check a working demo here: DEMO