我有以下数组:
var myArray = [
{"cartItems": {"paramA1": 25, "paramA2": 35}},
{"cartShippingCost": {"paramB1": 4, "paramB2": 152, "paramB3": 536, "paramB4": 56}},
{"cartSpecialRequirements": {"paramC1": 432}},
{"cartPostage": {"paramD1": 56, "paramD2": 6537}},
{"uid": {"paramE1": 545}},
{"tel": 7778798548}
];
然后我将上面的'cart'分组到对象键中:
var cartItems = myArray.filter(hasCartProperty);
var nonCartItems = myArray .filter(function (x) {
return !hasCartProperty(x);
});
function hasCartProperty(x) {
return Object.keys(x).some(function (x) {
return x.indexOf('cart') > -1;
});
}
if(Object.keys(cartItems).length > 0) {
cartItems.title = "Shopping Cart Items:";
}
if(Object.keys(nonCartItems).length > 0) {
nonCartItems.title = "Non Cart Items:";
}
$scope.data = [cartItems, nonCartItems];
然后我执行ng-repeat:
<div x-ng-repeat="myItem in data">
<p>{{myItem.title}}</p>
<p x-ng-repeat="(key, value) in myItem">
{{value}}
</p>
</div>
显示为:
Shopping Cart Items:
{"cartItems": {"paramA1": 25, "paramA2": 35}}
{"cartShippingCost": {"paramB1": 4, "paramB2": 152, "paramB3": 536, "paramB4": 56}}
{"cartSpecialRequirements": {"paramC1": 432}}
{"cartPostage": {"paramD1": 56, "paramD2": 6537}}
Non Cart Items:
{"uid": {"paramE1": 545}}
我如何显示为:
Shopping Cart Items:
cartItems:
{"paramA1": 25,
"paramA2": 35}
cartShippingCost":
{"paramB1": 4, "paramB2": 152,
"paramB3": 536, "paramB4": 56}
cartSpecialRequirements:
{"paramC1": 432}
cartPostage:
{"paramD1": 56,
"paramD2": 6537}
Non Cart Items:
uid:
{"paramE1": 545}
tel:
{7778798548}
答案 0 :(得分:1)
使用预标记和自定义格式函数formatValue():
<div x-ng-repeat="myItem in data">
<p>{{myItem.title}}</p>
<pre x-ng-repeat="(key, value) in myItem">{{formatValue(value)}}</pre>
</div>
...
$scope.formatValue = function(val) {
var firstProp = Object.keys(val)[0];
return firstProp + ":\r\n" + $filter("json")(val[firstProp]);
};
不要忘记将$ filter添加到您的控制器依赖项中:
.controller("defaultCtrl", function ($scope, $filter) {
结果: