[英]Pull value from JSON key value pair using AngularJS
Angular的ngRepeat中有沒有辦法根據其鍵將值從JSON數組中提取出來。 我使用以下JSON結構,並希望為每個對象輸出“名稱2”的關聯值。
{
"Items": [
{
...
"Attributes": [
{
"Name": "Name 1",
"Value": "123"
},
{
"Name": "Name 2",
"Value": "456"
},
{
"Name": "Name 3",
"Value": "789"
}
]
},
{
...
"Attributes": [
{
"Name": "Name 1",
"Value": "987"
},
{
"Name": "Name 2",
"Value": "654"
},
{
"Name": "Name 3",
"Value": "321"
}
]
},
{
...
"Attributes": [
{
"Name": "Name 1",
"Value": "246"
},
{
"Name": "Name 2",
"Value": "369"
},
{
"Name": "Name 3",
"Value": "135"
}
]
}
]
}
這樣嘗試
angular.forEach(data.Items,function(value,key){
angular.forEach(value,function(v){
if(v.name == "Name 2")
console.log(v);
}
})
這是一個例子。 它將打印“名稱2”的值 :
<body ng-app="myApp">
<div ng-controller="myCtrl">
<div ng-repeat="item in records.Items">
<div ng-repeat="singleAttribute in item.Attributes">
<div ng-if="singleAttribute.Name === 'Name 2'">
{{singleAttribute.Value}}
</div>
</div>
</div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = {
"Items": [
{
"Attributes": [
{
"Name": "Name 1",
"Value": "123"
},
{
"Name": "Name 2",
"Value": "456"
},
{
"Name": "Name 3",
"Value": "789"
}
]
},
{
"Attributes": [
{
"Name": "Name 1",
"Value": "987"
},
{
"Name": "Name 2",
"Value": "654"
},
{
"Name": "Name 3",
"Value": "321"
}
]
},
{
"Attributes": [
{
"Name": "Name 1",
"Value": "246"
},
{
"Name": "Name 2",
"Value": "369"
},
{
"Name": "Name 3",
"Value": "135"
}
]
}
]
};
});
</script>
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.