【问题标题】:Filter a list based on a dropdown choice that matches an object property根据与对象属性匹配的下拉选项过滤列表
【发布时间】: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


【解决方案1】:

ng-optionas一起使用,这样您就可以更新ng-model中的name。然后在ng-repeat的过滤条件中使用列表的ng-model

看到这个example

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

 selceted value is {{mySelectedChoice}}

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

【讨论】:

  • 是的,as 选项正是我想要的!您的代码示例完美地说明了这一点!
【解决方案2】:

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

在我的&lt;li&gt; 标记中,我只需将filter:{propertyIWantToMatchOn: mySelectedChoice} 更改为filter:{propertyIWantToMatchOn: mySelectedChoice.name}

谢谢大家!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-18
    • 2019-12-13
    • 2013-07-05
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2021-08-10
    • 2014-09-02
    相关资源
    最近更新 更多