根据与对象属性匹配的下拉选项筛选列表

时间:2015-08-12 03:58:07

标签: javascript angularjs

我的页面上有一个项目列表(使用ng-repeat的li元素)和一个下拉菜单(使用ng-options选择元素)。当下拉选项与项目上的特定属性匹配时,我只希望显示那些匹配的项目。

列表项对象如下所示:

var foo = {
    someProperty: 'someValue',
    someOtherProperty: 'someOtherValue',
    items: [{
        propertyIWantToMatchOn: 'someImportantValue', /* Note that there will be a lot of items, but they all contain this property */
        someDisplayText: 'this can be arbitrary'
    }]
};

有时,列表项的propertyIWantToMatchOn值为someImportantValue,有时它们的值为someOtherImportantValue

我的选择列表如下所示:

var myChoices = [
    {name: 'someImportantValue'},
    {name: 'someOtherImportantValue'}
];

我的选择下拉列表如下所示:

<select ng-model="mySelectedChoice" ng-options="myChoice.name for myChoice in myChoices"></select> 

我的列表项目生成如下:

<ul>
    <li ng-repeat="item in foo.items | filter:{propertyIWantToMatchOn: mySelectedChoice}">{{item.someDisplayText}}</li>
</ul>

使用当前过滤器,无论选择何种选项,我的列表中都不会显示任何内容。如果我删除过滤器,则无论选择什么,所有项目都会显示。

如何修改过滤器/我的代码,以便我只能显示其属性与下拉列表中的选项匹配的项目?

干杯!

编辑:如果我在控制器中将mySelectedChoice硬编码为与我要匹配的属性值匹配的字符串,则列表会正确过滤。所以我想现在我需要弄清楚如何将选择保存为name的值而不是对象本身。

2 个答案:

答案 0 :(得分:2)

ng-optionas一起使用,以便更新name中的ng-model。然后在过滤条件{{1}中使用ng-model列表1}}。

请参阅此example

ng-repeat

答案 1 :(得分:0)

我设法解决了自己的问题。只需要一点点选择!

在我的<li>标记中,我只需将filter:{propertyIWantToMatchOn: mySelectedChoice}更改为filter:{propertyIWantToMatchOn: mySelectedChoice.name}

谢谢你们!

相关问题