我正在尝试让我的 Angular Controller 在处理 JSON 对象数组的方式上更加通用。
目前我定义了以下内容:
$scope.Data = [];
我在模板中提取数据,如下所示:
ng-repeat="item in Data.category[3].values
我的 JSON 看起来像:
"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
}]
}]
我想做的不是使用以下方式访问特定索引:
Data.category[3].values
我想遍历类别并获取索引项列表,以便我可以使用:
Data.category[Color].values
在列表中找到颜色,我可以带回该特定元素的值,这可能吗?
最佳答案
您可以使用filter
代替,您也可以通过范围动态传递Color
值。
标记
ng-repeat="item in (Data.category| {name: 'Color'}: true)[0].values
更新
您可以通过另一个作用域变量动态传递Color
变量,例如$scope.color = 'Color'
,这样ng-repeat就会变成
HTML
ng-repeat="item in (Data.category| {name: color}: true)[0].values
关于javascript - AngularJS JSON 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30616262/