Snoopy14 Snoopy14 - 6 months ago 60
AngularJS Question

AngularJs Search with drop down filter

How would you go about creating a refined search? With the code below, the filter acts on both of the columns. For example, if you type in John, you will get both John Smith & Smith John. I want to use a dropdown as a filter by. I looked at other posts which mentioned filter: object.value or something.

I think I need to set the dropdown to a value which is then fed to the text box and filtered to the table.

HTML

<div ng-app="searchApp" ng-controller="searchCtrl">
<br>
<br>
<input type="text" ng-model="searchData">

<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>


<select>
<option value="">FilterBy</option>
<option value="">FirstName</option>
<option value="">LastName</option>
</select>



<tr ng-repeat="name in names | filter:searchData">

<td>{{name.firstName}}</td>
<td>{{name.lastName}}</td>
</tr>
</tbody>
</table>
</div>

<script src=" search.js " type="text/javascript "></script>




.JS

var searchApp = angular.module('searchApp', []);
searchApp.controller('searchCtrl', function($scope) {

$scope.names = [
{"firstName":"John","lastName":"Smith"},
{"firstName":"Smith","lastName":"John"},
{"firstName":"John","lastName":"Doe"},
{"firstName":"Doe","lastName":"Jane"}
];



});

Answer

I added an ng-change to the filter drop down and set the filter object on that function call.
<select ng-model="by" ng-change="filter(by)"> <option value="">FilterBy</option> <option value="firstName">FirstName</option> <option value="lastName">LastName</option> </select>

$scope.filter = function(by){ if(by){ $scope.filterData = { }; $scope.filterData[by] = $scope.searchData;
}else{ $scope.filterData = {}; } };

Here is a link to a working example http://codepen.io/mkl/pen/GqpxGZ