【发布时间】:2016-02-13 01:07:24
【问题描述】:
我对 JS 和 AngularJS 的陡峭学习曲线非常陌生。 我有许多具有以下(相关)属性的对象数组:
$scope.myRecs = [{country: 'Ireland', city: 'Dublin', type: 'Food'},
{country: 'Italy', city: 'Rome', type: 'Activity'},
{country: 'Australia', city: 'Sydney', type: 'Bar/Pub'}];
我需要将数组显示如下:
<div ng-repeat="rec in myRecs"></div>
我需要能够使用三个 Ionic HTML 选择元素(每个属性一个)过滤数组,选项如下:
<select ng-model = "selectedCountry">
<option value="All"></option
<option ng-repeat="rec in myRecs | orderBy: 'country' | unique: 'country'">{{rec.country}}</option>
</select>
<select ng-model = "selectedCity">
<option value="All"></option>
<option ng-repeat="rec in myRecs | orderBy: 'city' | unique: 'city'">{{rec.city}}</option>
</select>
<select ng-model = "selectedType">
<option value="All">All</option>
<option ng-repeat="rec in myRecs | orderBy: 'type' | unique: 'type'">{{rec.type}}</option>
</select>
注意:我已经使用 angular-filter 库中的唯一过滤器删除了选择选项的重复项。
我需要通过在其他两个选择选项中选择的内容来过滤每个选择选项,所以我尝试向每个选项添加这样的过滤器:
<select>
<option ng-repeat="rec in myRecs | orderBy: 'type' | unique: 'type' | filter: selectedCountry && selectedCity">{{rec.type}}</option>
</select>
还有不同类型的语法,像这样:
filter: {city:selectedCity,country:selectedCountry}
或
filter: selectedCity || selectedCountry
或
filter: selectedCity | filter: selectedCountry
我不知道哪个是正确的语法,或者这是否是正确的方法。
我也尝试了相同的语法来过滤显示的数组:
<div ng-repeat="rec in myRecs | filter: selectedCountry && selectedCity && selectedType"></div>
或
<div ng-repeat="rec in myRecs | filter: selectedCountry || selectedCity || selectedType"></div>
等等……
我得到的结果很奇怪。选择一个国家,然后过滤城市选项的 ng-repeat,但类型选项的 ng-repeat 将始终为空。我觉得当涉及两个过滤器而不是三个过滤器时它可以工作,但是如果我先选择一个类型然后尝试另一个选择,那里什么都没有:/
这是尝试像这样过滤数组的正确方法还是有人可以解释更好的方法?
如果我不希望它们在选择数组时过滤数组,我应该为 All 选项赋予什么值?
谢谢!
【问题讨论】:
-
更新了我的答案。第一次尝试是错误的(抱歉)。我也添加了一个工作示例。
标签: javascript arrays angularjs filter ionic-framework