【发布时间】:2015-08-12 03:58:06
【问题描述】:
我的页面上有一个项目列表(使用 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 的值而不是对象本身。
【问题讨论】:
-
您想在 ng-repeat 中显示什么?基于属性IWantToMatchOn 你想列出什么?项目是否只有“propertyIWantToMatchOn”?举一个预期输出的例子。
-
感谢您了解这一点。这实际上与我想要显示的内容无关,我只想为属性与下拉选择匹配的所有项目显示项目显示文本:) 我已经更新了我的代码以包含我想要显示的内容。
-
我的解决方案解决了将名称保存为对象的问题。您可以使用ng-option更新ngmodel中的名称。
标签: javascript angularjs