简体   繁体   English

基于下拉选择的angularJS中的条件模型绑定

[英]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 无论用户选择了什么,搜索都将基于此,搜索可以是searchQuery.idsearchQuery.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. 我尝试使用来自使用getter/setter的类似主题的代码,但是我似乎无法使其正常工作。

How do I do this? 我该怎么做呢?

You can be search object inside controller like $scope.search = {} and then place search object over that filter. 您可以像$scope.search = {}这样的控制器内的search对象,然后将搜索对象放在该过滤器上。

<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. 因此,当您更改下拉值时,请清除search对象。 So that search would be more accurate. 这样搜索将更加准确。

Demo Plunkr Demo Plunkr

if I'm not mistaken, you can do this : 如果我没记错的话,可以这样做:

ng-repeat="user in users | .... | filter:conditionalSearch()"

and then in your controller / link add this : 然后在您的控制器/链接中添加以下内容:

$scope.conditionalSearch = function() {
    if ($scope.searchType == 'id') return { .. condition 1 .. }
    if ($scope.searchType == 'firstName') return { .. condition 2 .. }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM