Javascript 基于选择的角度过滤器特定字段

Javascript 基于选择的角度过滤器特定字段,javascript,angularjs,Javascript,Angularjs,我想根据选择和输入过滤一个ng repeat。如果输入设置为all,则对所有字段进行过滤;如果输入设置为不同的选择值,则仅对该字段进行过滤 我有这样的HTML <input type="search" class="form-control" id="searchBox" ng-model="searchText"> <select class="form-control" id="searchType" name="searchType" ng-model="searchT

我想根据选择和输入过滤一个
ng repeat
。如果输入设置为
all
,则对所有字段进行过滤;如果输入设置为不同的选择值,则仅对该字段进行过滤

我有这样的HTML

<input type="search" class="form-control" id="searchBox" ng-model="searchText">

<select class="form-control" id="searchType" name="searchType" ng-model="searchType">
  <option value="all">All Fields</option>
  <option value="locationCode">Location Code</option>
</select>

<!-- more code -->

<tr ng-if="!searchAll" ng-repeat="location in locations | filter:{searchType: searchText}" ts-repeat>
<tr ng-if="searchAll" ng-repeat="location in locations | filter:searchText" ts-repeat>
当选择了
all
时,我的过滤器工作正常,但当选择另一个值时,我的过滤器完全不显示数据。但是,如果我在第一个
ng if
中对
searchType
中的一个字段值进行硬编码,它确实可以工作


我遗漏了什么明显的东西?

我不认为对象中的左侧值是可变的。所以当你这么做的时候

location in locations | filter:{searchType: searchText}
您希望筛选器查找名为
searchType
的属性,而不是
locationCode

我认为最简单的修复方法是在控制器中创建一个过滤器函数,并在其中处理开关

比如:

$scope.propertyFilter = function(item) {
  return item[$scope.searchType] == $scope.searchText;
} 
然后在你的模板里面

location in locations | filter:propertyFilter
我还想知道将对象作为字符串处理是否可行。大概是这样的:

location in locations | filter:{{"{" + searchType + ":" + searchText + "}"}}

我仍在努力让它像我想要的那样工作,但我相信你的第一个解决方案让我朝着正确的方向前进。
location in locations | filter:{{"{" + searchType + ":" + searchText + "}"}}