AngularJS中使用data-ng-repeat实现复杂表格的问题求助
嘿,我懂你现在的困扰——用AngularJS的ng-repeat做这种带嵌套对象的表格确实容易卡壳。你的问题核心在于当前代码只盯着第一个店铺的prices遍历,没法把每个店铺对应的产品价格匹配上。我来帮你调整一下代码结构,完美解决这个问题:
首先,咱们先理清楚需求:要做一个表格,表头是各个店铺名称,每行对应一个产品,每个单元格是对应店铺的该产品价格,最后还要加上店铺评论行对吧?
解决方案1:控制器预处理产品列表
先在你的控制器里把所有产品名称提取出来(假设所有店铺的产品都是一致的,从第一个店铺的prices里取就行),这样模板里用起来更方便:
$scope.test = [ {store: "NYC store", comment: "comment1", prices: { "product1": "12", "product2": "10", "product3": "71"} }, {store: "Texas store", comment: "comment2", prices: { "product1": "15", "product2": "9", "product3": "68"} } ]; // 提取所有产品名称 $scope.products = Object.keys($scope.test[0].prices);
然后修改模板代码:
<table style="border-collapse: collapse;" border="1"> <!-- 表头:产品名称 + 各个店铺 --> <tr> <th>产品名称</th> <th data-ng-repeat="shop in test">{{ shop.store }}</th> </tr> <!-- 产品价格行:遍历每个产品,再遍历每个店铺取对应价格 --> <tr data-ng-repeat="product in products"> <td>{{ product }}</td> <td data-ng-repeat="shop in test">{{ shop.prices[product] }}</td> </tr> <!-- 店铺评论行 --> <tr> <td>店铺评论</td> <td data-ng-repeat="shop in test">{{ shop.comment }}</td> </tr> </table>
解决方案2:用自定义过滤器(无需控制器预处理)
如果你不想在控制器里额外处理产品列表,可以自定义一个AngularJS过滤器来获取对象的键,这样模板里就能直接用了:
先在你的模块里注册过滤器:
angular.module('yourAppName').filter('objectKeys', function() { return function(obj) { return Object.keys(obj); }; });
然后模板代码可以写成这样:
<table style="border-collapse: collapse;" border="1"> <tr> <th>产品名称</th> <th data-ng-repeat="shop in test">{{ shop.store }}</th> </tr> <!-- 直接用过滤器获取产品列表 --> <tr data-ng-repeat="product in test[0].prices | objectKeys"> <td>{{ product }}</td> <td data-ng-repeat="shop in test">{{ shop.prices[product] }}</td> </tr> <tr> <td>店铺评论</td> <td data-ng-repeat="shop in test">{{ shop.comment }}</td> </tr> </table>
为什么原来的代码不行?
你之前的代码里,价格行只循环了test[0].prices,所以只能拿到第一个店铺的价格键值对,而且每行只能显示第一个店铺的价格+产品名称,根本没地方放其他店铺的对应价格。现在的写法是先遍历产品,再针对每个产品遍历所有店铺取价格,这样就能把每个店铺的产品价格都对应上啦。
内容的提问来源于stack exchange,提问作者cinnamon
相关产品推荐
相关产品推荐

