angularjs: change filter options dynamically
You can define ng-model
like: ng-model="search[filter]"
to change dynamically to which variable it should be binded (where filter
is another $scope
variable).
See the fiddle:http://jsfiddle.net/lopisan/vzQKk/1/
You have to add this line to the controller:
$scope.search = {name:'', phone:'', $:''};
And change input:
<input type="text" ng-model="search[filter]">
Here's one approach - there are probably others.
<div ng-app> <div ng-controller="MainCtrl"> <div style="background-color:#FAE8F1"> <hr> <label>Filter</label> <input type="text" ng-model="multi"> by {{filter}} <br> <ul> <li><a href="" ng-click="changeFilterTo('$')">Any</a></li> <li><a href="" ng-click="changeFilterTo('name')">By Name</a></li> <li><a href="" ng-click="changeFilterTo('phone')">By phone</a></li> </ul> <hr> </div> <table class="table"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:getFilter()"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> </div></div>
Javascript:
function MainCtrl($scope, $http) { $scope.friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}]; $scope.filter = "$"; $scope.multi = ""; $scope.changeFilterTo = function(pr) { $scope.filter = pr; } $scope.getFilter = function() { switch ($scope.filter) { case 'name': return {name: $scope.multi}; case 'phone': return {phone: $scope.multi}; default: return {$: $scope.multi} } }};
Here's another simple approach using radio buttons
<input type="text" ng-model="search[filter]"><label>filter by these</label><label>Any <input type="radio" ng-model="filter" ng-init="filter = '$'" value="$"></label><label>name<input type="radio" ng-model="filter" value="name"></label><label>phone<input type="radio" ng-model="filter" value="phone"></label>