Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.js select filter type of input box

I am using angular.js for quite short time, and sometimes i have a feeling, that I know nothing about html and javascript because of angular's odds when hitting things that in my imagination should, and probably ARE very simple.

Here is my headache:

my currents controller scope.persons is a list of... persons aquired by factory from backend. it shows nicely with ng-repeat, and filters with input:

<input ng-model='query.firstname'> // search by firstname
<input ng-model='query.lastname'> // search by lastname

<ul>
    <li ng-repeat='person in persons | filter: query'> firstname: {{person.firstname}}, lastname: {{person.lastname}}
</ul>

but i want to make it possible to choose from what should be filter.

something like:

<select> 
    <option value='query.firstname'> by firstname </option>
    <option value='query.lastname'> by lastname </option>

I tried to mess around in a lot of ways, which Im embarassed to show :), but im lost how to connect select with input ng-model...

thanks for help, in advance.

like image 634
Jarema Avatar asked Nov 23 '25 10:11

Jarema


1 Answers

You can try this approach. HTML:

<select ng-model="filter">
    <option value='firstname'>by firstname </option>
    <option value='lastname'>by lastname </option>
</select>

<input ng-model='query'>

<ul>
    <li ng-repeat='person in persons | filter: getFilter()'> firstname: {{person.firstname}}, lastname: {{person.lastname}}
</ul>

and in controller construct filter expression dynamically:

$scope.getFilter = function() {
    var filter = {};
    filter[$scope.filter] = $scope.query;
    return filter;
};

Demo: http://plnkr.co/edit/W5dIMYp3C8p3Yid9iglE?p=preview

like image 119
dfsq Avatar answered Nov 24 '25 23:11

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!