AngularJS中ng-repeat循环时通过itemName映射展示描述的方法
解决方案:通过itemName映射显示商品描述
嘿,我来帮你搞定这个问题!你已经成功渲染了商品名称和数量,要关联显示对应的描述,这里有两种直观好用的方法,我都给你整理好了:
方法1:用辅助函数实时匹配描述
这种方法适合快速修改,直接在控制器里定义一个函数,根据当前商品名去items数组里找对应的描述:
修改后的JavaScript代码
var c = angular.module('myApp', []); c.controller("myCtrl", function($scope) { $scope.data = { count: { "Item 1": 10, "Item 2": 20 }, items: [ { "itemDescription": "Item 1的详细描述", "itemName": "Item 1" }, { "itemDescription": "Item 2的详细描述", "itemName": "Item 2" } ] }; $scope.name = "Demo"; // 添加辅助函数:根据商品名获取对应描述 $scope.getDescription = function(itemName) { // 从items数组中匹配对应的商品对象 var matchedItem = $scope.data.items.find(item => item.itemName === itemName); // 找到就返回描述,没找到就返回空字符串避免显示undefined return matchedItem ? matchedItem.itemDescription : ''; }; });
修改后的HTML代码
把原本空的描述列替换成调用辅助函数:
<html> <head> <script data-require="angular.js@1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-app="myApp" ng-controller="myCtrl"> <h1>Hello Plunker!</h1> <table border="2"> <tr> <td>Name</td> <td>Description</td> <td>Count</td> </tr> <tr ng-repeat="(key,value) in data.count"> <td>{{key}}</td> <!-- 调用辅助函数填充描述 --> <td>{{getDescription(key)}}</td> <td>{{value}}</td> </tr> </table> </body> </html>
方法2:提前合并数据(更推荐,性能更优)
如果商品数据量比较大,每次循环调用find可能有性能损耗,这种情况可以提前把count和items合并成一个统一数组,再直接遍历:
修改后的JavaScript代码
var c = angular.module('myApp', []); c.controller("myCtrl", function($scope) { var rawData = { count: { "Item 1": 10, "Item 2": 20 }, items: [ { "itemDescription": "Item 1的详细描述", "itemName": "Item 1" }, { "itemDescription": "Item 2的详细描述", "itemName": "Item 2" } ] }; $scope.name = "Demo"; // 合并数据成统一的商品数组 $scope.products = rawData.items.map(item => ({ name: item.itemName, description: item.itemDescription, count: rawData.count[item.itemName] || 0 // 没有对应数量就显示0 })); });
修改后的HTML代码
直接遍历合并后的products数组:
<html> <head> <script data-require="angular.js@1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-app="myApp" ng-controller="myCtrl"> <h1>Hello Plunker!</h1> <table border="2"> <tr> <td>Name</td> <td>Description</td> <td>Count</td> </tr> <tr ng-repeat="product in products"> <td>{{product.name}}</td> <td>{{product.description}}</td> <td>{{product.count}}</td> </tr> </table> </body> </html>
两种方法都能实现你的需求,方法2的代码可读性和性能更好,更推荐使用哦!
内容的提问来源于stack exchange,提问作者Alexa
相关产品推荐
相关产品推荐

