【问题标题】:AngularJS access JSON index values dynamicallyAngularJS 动态访问 JSON 索引值
【发布时间】:2015-06-03 21:35:29
【问题描述】:

我的范围数据:

$scope.data = 
 "category": [{
"name": "cat1",
"behaviour": "normal",
"selected": 0,
"values": [{
    "label": "define",
    "count": 6
}]
}, {
"name": "cat2",
"behaviour": "normal",
"selected": 0,
"values": [{
    "label": "type",
    "count": 6
}]
}, {
"name": "Company",
"behaviour": "multi-select",
"selected": 0,
"values": [{
    "label": "VW",
    "count": 4
}, {
    "label": "Renault",
    "count": 1
}, {
    "label": "Fiat",
    "count": 1
}]
}, {
"name": "Make",
"behaviour": "multi-select",
"selected": 0,
"values": [{
    "label": "Gold",
    "count": 3
}]
}, {
"name": "Color",
"behaviour": "normal",
"selected": 0,
"values": [{
    "label": "White",
    "count": 3
}, {
    "label": "Blue",
    "count": 2
}, {
    "label": "Green",
    "count": 1
}]
}]

如何在不使用索引的情况下访问“名称”:“值”?因为数据可能会增长和变化,我不想在任何地方分配索引值?我仍然想过滤,例如:

| {name: 'Make'}: true)

在我的标记中显示

【问题讨论】:

标签: angularjs multidimensional-array angularjs-scope angularjs-ng-repeat


【解决方案1】:

所以json不正确,我更正了(下次你可以使用这个网站看看你的json是否有效JSONVALIDATOR) 如果您想访问名称的值,请执行此操作

在您的控制器中:

$scope.data = [
{
    "name": "cat1",
    "behaviour": "normal",
    "selected": 0,
    "values": [
        {
            "label": "define",
            "count": 6
        }
    ]
},
{
    "name": "cat2",
    "behaviour": "normal",
    "selected": 0,
    "values": [
        {
            "label": "type",
            "count": 6
        }
    ]
},
{
    "name": "Company",
    "behaviour": "multi-select",
    "selected": 0,
    "values": [
        {
            "label": "VW",
            "count": 4
        },
        {
            "label": "Renault",
            "count": 1
        },
        {
            "label": "Fiat",
            "count": 1
        }
    ]
},
{
    "name": "Make",
    "behaviour": "multi-select",
    "selected": 0,
    "values": [
        {
            "label": "Gold",
            "count": 3
        }
    ]
},
{
    "name": "Color",
    "behaviour": "normal",
    "selected": 0,
    "values": [
        {
            "label": "White",
            "count": 3
        },
        {
            "label": "Blue",
            "count": 2
        },
        {
            "label": "Green",
            "count": 1
        }
    ]
}
];

在您的 HTML 中

      <div ng-repeat="d in data"> {{d.name}} </div>

如果您想显示名称为“公司”的对象的值,您可以像在我的工作 CodePen 中那样执行此操作:

只需添加一个新的 ng-repeat :

   <div ng-repeat="d in data"> {{d.name}} 
         <div ng-if="d.name == 'Company'" ng-repeat="da in d.values">{{da.label}}</div>      
  </div>

【讨论】:

  • 我需要能够指定 name=Company 例如
  • 如果这是公司,你会做一些不同的事情吗?是你的意思吗?
  • 所以不,我会这样做:
    并显示一个计数值,例如跨度>
  • Codepen 添加到我的答案中
【解决方案2】:

首先,您的数据格式不是正确的 JSON 格式,请通过在线验证器运行。

要访问该元素,您只需通过:

<li ng-repeat="item in data">
    {{ item.name }} {{ item.behaviour }} etc...
</li>

去掉 $scope.data 中的类别...让它成为一个像典型 JSON 值一样的数组。

【讨论】:

  • @carton - 哈哈,一定是同时发帖的.. 很简单的问题
  • 我不能玩这个结构:)
猜你喜欢
相关资源
最近更新 更多
热门标签