Programmer Programmer - 4 months ago 14
Javascript Question

filter is not working inside angular controller

I want to filter list of object using filter object inside angular controller. But it's give me filtered list. It should return second object.

This is my code sample

app.controller('MainCtrl', function($scope, $filter) {
$scope.list=[
{

"job_id": 2,
"description": "Bid for Job 2",
"price": 115,
"butler_id": 60,
"butler_name": "Butler Client 1",
"service_price": 500,
"material_price": 900,
"date_created": "23 Apr 1993"
},
{

"job_id": 2,
"description": "sfcs",
"price": 555,
"butler_id": 70,
"butler_name": "Butler Client 2",
"service_price": 666,
"material_price": 666,
"date_created": "23 Apr 1993"
}
];

$scope.filter ={"butler_name":"","service_price":"","material_price":"6","price":"","created_date":"","description":""};

var getFiltered = $filter('filter')($scope.list, $scope.filter);
$scope.filteredBids = getFiltered;

});


Plunker link

Answer

You are passing all property in filter, and Angular consider AND, so you are not getting any result.

You have to create properties according to your filter.

 var filterParams = {};
        if ($scope.filter.butler_name.trim() !== "") {
            filterParams.butler_name = $scope.filter.butler_name;
        }
        if ($scope.filter.service_price.trim() !== "") {
            filterParams.service_price = $scope.filter.service_price;
        }
        if ($scope.filter.material_price.trim() !== "") {
            filterParams.material_price = $scope.filter.material_price;
        }
        if ($scope.filter.price.trim() !== "") {
            filterParams.price = $scope.filter.price;
        }
        if ($scope.filter.created_date.trim() !== "") {
            filterParams.created_date = $scope.filter.created_date;
        }
        if ($scope.filter.description.trim() !== "") {
            filterParams.description = $scope.filter.description;
        }
        var getFiltered = $filter('filter')($scope.list, filterParams);
        $scope.filteredBids = getFiltered;

Updated link