简体   繁体   English

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

[英]Angular filter specific field based upon select

I would like to filter an ng-repeat that I have based upon a select and an input. 我想过滤基于选择和输入的ng-repeat If the input is set to all then filter on all fields, if it is set to a different select value then only filter on that field. 如果将输入设置为all则对所有字段进行过滤;如果将输入设置为不同的选择值,则仅对该字段进行过滤。

I have HTML that looks like this 我有看起来像这样的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>

I'm also updating $location.search() when either the select or input are changed, but this should be the relevant part of my controller: 当选择或输入更改时,我也在更新$location.search() ,但这应该是控制器的相关部分:

$scope.$watch('searchType', function(value) {
  $location.search('t', value).replace();
  $scope.searchAll = $scope.searchType === 'all';
});

My filter works properly when all is selected, but shows no data at all when another value is selected. 我的过滤器工作正常时, all选择,但目前尚无数据都在选择另一个值。 However, it does work if I hardcode one of the field values in searchType in the first ng-if . 但是,如果我在第一个ng-if中将searchType中的一个字段值硬编码,则它确实可以工作。

What obvious thing am I missing? 我想念什么明显的东西?

I don't think the left hand value in an object can be variable. 我认为对象中的左手值不能是可变的。 So when you do this 所以当你这样做

location in locations | filter:{searchType: searchText}

You a expecting the filter to find a property named searchType instead of locationCode 您期望过滤器找到名为searchType的属性,而不是locationCode

I think the simplest fix would be to create a filter function in the controller and handle the switch in there. 我认为最简单的解决方法是在控制器中创建过滤器功能并处理其中的开关。

Something like : 就像是 :

$scope.propertyFilter = function(item) {
  return item[$scope.searchType] == $scope.searchText;
} 

And then inside your template 然后在您的模板中

location in locations | filter:propertyFilter

I also wonder if treating the object as a string might work. 我也想知道是否可以将对象视为字符串。 Something like this : 像这样的东西:

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

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

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