【问题标题】:Is it possible to mix elements in ng-options with and without groups?是否可以在 ng-options 中使用和不使用组来混合元素?
【发布时间】:2016-07-11 09:06:21
【问题描述】:

直到 Angular 1.4.4(或者可能更进一步),可以在 ng-options 中使用组,如果组名是空字符串或 null/未定义,它会在组之外创建一个选项。在新版本 1.5.7 中有没有办法做到这一点?根据this question,接受的答案建议添加一个新组来收集所有非组元素,但这不符合我的规范。我当然需要一开始不属于组的选项,然后是组内的元素,迁移到新版本后仍然可以正常工作。

Here is the fiddle 用于链接问题,我想在该示例中删除名为 No_Group 的组。

ng-options="d.title group by (d.group ==='' ? 'No_Group' : d.group) for d in data"

$scope.data = [
        {
            group:"",
            title:"No GroupA"
        },
        {
            group:"Group_1",
            title:"1"
        },
        {
            group:"",
            title:"No GroupB"
        },
        {
            group:"Group_2",
            title:"2"
        },
        {
            group:"",
            title:"No GroupC"
        }
]

【问题讨论】:

  • 您只能使用 (d.group ==='' ? '' : d.group) 而不是 (d.group ==='' ? 'No_Group' : d.group)。
  • 你不要在使用 ng-options 之前从数组中删除值
  • 正如我所说,使用空字符串会创建空组,所以它的字面意思是 null 作为组的名称,这就是我想要摆脱的.
  • 这就是我的意思,如果 gropu 为空,则不要使用删除它,然后在 ng-options 中使用
  • 我很难理解你的句子

标签: javascript angularjs ng-options angularjs-ng-options


【解决方案1】:

原来我需要将 undefined 作为组提供,空字符串或 null 不再起作用。一种选择是将html部分编写如下:

ng-options="d.title group by (d.group ? d.group : undefined) for d in data"

但是由于我知道哪些对象将在组之外,所以我通过根本不将它们添加到组对象来更优雅地解决问题,这将对应于本示例代码中的以下内容:

$scope.data = [
        {
            title:"No GroupA"
        },
        {
            group:"Group_1",
            title:"1"
        },
        {
            title:"No GroupB"
        },
        {
            group:"Group_2",
            title:"2"
        },
        {
            title:"No GroupC"
        }
]

查看导致此行为的 issue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2012-05-15
    • 2019-11-06
    • 2010-10-16
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多