我有以下JSON数据,我希望Angular为ngRepeat
内的每个key
执行Specification
,并按照与它们相同的顺序显示对象:
"Specification": {
"Screen": "15.4\" Retina display",
"Resolution": "2880 x 1800",
"HDD": "512GB SSD",
"RAM": "16GB RAM",
"CPU": "Intel Core i7 2.30 Ghz Processor",
"Software": "Mac OS X 10.9 Mavericks"
}
这是我的HTML:
<ul>
<li ng-repeat="(key, value) in selectedProduct.Specification">
<span ng-class="{{key | lowercase}}">{{value}}</span>
</li>
</ul>
上面的代码以随机顺序输出数据,而不是数组中出现的顺序。
答案 0 :(得分:3)
某些浏览器(例如Chrome)会按字母顺序重新排列密钥,因此没有可靠的跨浏览器方式来保留对象的密钥顺序。您应该将其转换为数组,或者单独指定键顺序(例如,作为单独的数组)。
<强>更新强>
正如runTurm正确指出的那样,在ngRepeat
中,特别是键由Angular按字母顺序排序。因此,保留特定订单的最简单方法是使用单独的数组按所需顺序保存密钥:
/* CONTROLLER: */
$scope.keys = ["Screen", "Resolution", "HDD", "RAM", "CPU", "Software"];
$scope.selectedProduct = {
Specification: {
...
},
...
};
<!-- VIEW: -->
<ul>
<li ng-repeat="key in keys">
<span class="{{key | lowercase}}">{{selectedProduct.Specification[key]}}</span>
</li>
</ul>
如果您发现它更具可读性,或者您计划在多个地方使用selectedProduct.Specification[key]
,则可以使用ngInit
将其别名为value
:
<li ng-repeat="key in keys" ng-init="value=selectedProduct.Specification[key]">
<span class="{{key | lowercase}}">{{value}}</span>
</li>
另请参阅此 short demo 。
答案 1 :(得分:1)
您可以创建一个过滤器,该过滤器将通过angular.forEach()
返回键值对象的数组对象表示。
<强> DEMO 强>
<强> JAVASCRIPT 强>
.controller('Ctrl', function($scope, $filter) {
var specs = {
"Screen": "15.4\" Retina display",
"Resolution": "2880 x 1800",
"HDD": "512GB SSD",
"RAM": "16GB RAM",
"CPU": "Intel Core i7 2.30 Ghz Processor",
"Software": "Mac OS X 10.9 Mavericks"
};
$scope.specs = $filter('keyValue')(specs);
})
.filter('keyValue', function() {
return function(object) {
var array = [];
angular.forEach(object, function(value, index) {
array.push({
value: value,
key: index
});
});
return array;
};
});
<强> HTML 强>
<ul>
<li ng-repeat="item in specs">
<span ng-class="{{item.key | lowercase}}">{{item.value}}</span>
</li>
</ul>
答案 2 :(得分:0)
您不能直接在ANgular中执行此操作,但可以修改绑定到视图的对象,也可以为其创建自定义过滤器。我使用Object.keys()方法返回键,然后将其用于计算对象。
angular.module('app', []).controller('controller', function($scope){
var data = {"Specification": {
"Screen": "15.4\" Retina display",
"Resolution": "2880 x 1800",
"HDD": "512GB SSD",
"RAM": "16GB RAM",
"CPU": "Intel Core i7 2.30 Ghz Processor",
"Software": "Mac OS X 10.9 Mavericks"
}};
var filter = Object.keys(data.Specification),
b = [];
angular.forEach(filter, function(key, value){
b.push(data.Specification[key]);
});
$scope.selectedProducts = b;
});
<强> Demo 强>