Carlos Miguel Colanta Carlos Miguel Colanta - 1 month ago 8
AngularJS Question

Conditional model binding in angularJS based from the drop down selection

Say that I have a dropdown that is bound to a model property that will be checked to determine the model that will bound to my textbox.

<select ng-model="searchType">
<option value="Id">Id</option>
<option value="Firstname">Firstname</option>
</select>


whatever the user picked, The search will be based off that and it could either be
searchQuery.id
or
searchQuery.Firstname


It is displayed like this:

<tr ng-repeat="user in users | orderBy:sortColumn:sortDescending | filter:searchQuery">
<td>{{ user.Id }}</td>
<td>{{ user.Firstname }}</td>
<td>{{ user.LastName }}</td>
</tr>


I tried to use the code from a similar topic that uses the
getter/setter
but I can't seem to make it work.

How do I do this?

Answer

You can be search object inside controller like $scope.search = {} and then place search object over that filter.

<select ng-model="searchType">
   <option value="Id">Id</option>
   <option value="Firstname">Firstname</option>
</select>
<input class="form-control" ng-model="search[searchType]" ng-disabled="!searchType.length"/>

<tr ng-repeat="user in users | orderBy:sortColumn:sortDescending | filter: search">
    <td>{{ user.Id }}</td>
    <td>{{ user.Firstname }}</td>
    <td>{{ user.LastName }}</td>
</tr>

Though above will work but if you change dropdown it will now work as intended. So do clear search object when you change the dropdown value. So that search would be more accurate.

Demo Plunkr