gpt4 book ai didi

javascript - AngularJS 根据选择的选择选项通过文本输入过滤对象数组

转载 作者:行者123 更新时间:2023-12-01 02:06:58 24 4
gpt4 key购买 nike

我无法让涉及文本输入、ng-repeat 和选择的特定 Angularjs 过滤设置正常工作,并且喜欢任何人的任何帮助
可以提供。

我有一个像这样的对象数组:

[{ id: '1', firstName: 'Charles', lastName: 'Charlston' }, ...]

我通过文本输入过滤数组,如下所示:
<input ng-model="searchText" />

<div ng-repeat="person in people | filter : searchText" ...

目前,这会针对“任何”属性值对人员对象数组进行排序,并且效果很好。

我想要实现的是能够更改我的 <input ng-model="searchText" /> 的属性根据 <option id="1" label="lastName" selected>Last Name</option> 过滤人员数组被选中。

我的选择如下所示:
<select class="filterSelect"
ng-model="selectedPropertyOption"
ng-options="prop.name for prop in peopleProperties"></select>

peopleProperties 看起来像这样:
$scope.peopleProperties = [{id: "1", name: "firstName"}, ...];
因此,与其在输入中键入:“charles”并获得与属性 id、fistName 或 lastName 匹配的结果,我需要能够从选择中选择一个选项,其中该选项是像“firstName”这样的属性名称,我想要过滤。然后,在输入中输入的任何内容都只会根据选择的选项过滤对象。

我希望这足够有道理!任何指导将不胜感激,在此先感谢您!

最佳答案

这是纯粹在 View 中指定过滤器不方便且有点“肮脏”(尽管可能)的时候之一。

我们需要的是一个可以采取以下形式的过滤器对象:

$scope.filter = { firstName: "foo" };

// or
$scope.filter = { lastName: "foo" };

// or - to reset the "filterBy" property
$scope.filter = { $: "foo" }; // or just "foo"

这在表达式中并不容易做到,所以最好在 Controller 中做到:
$scope.filter = {$: undefined}; // initial non-filtering value

$scope.setFilter = function(){
$scope.filter = {};
$scope.filter[$scope.selectedPropertyOption || '$'] = $scope.searchText;
};

然后,调用 setFiltersearchText 的每次更改都起作用的 selectedPropertyOption :
<input ng-model="searchText" ng-change="setFilter()" />

<select ng-model="selectedPropertyOption"
ng-options="prop.name as prop.name for prop in peopleProperties"
ng-change="setFilter()">
<option value="">All Fields</option>
</select>

<div ng-repeat="person in people | filter: filter">
{{person}}
</div>

Demo

关于javascript - AngularJS 根据选择的选择选项通过文本输入过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com