AngularJS合并对象数组并展示ID匹配关联用户数据问题咨询
实现步骤
你只需要对现有JS和HTML做少量修改即可完成需求,修改点如下:
1. 调整JS代码逻辑
修改内容如下:
- 给
viewMore方法接收传入的用户ID,同时存储选中的用户信息 - 新增筛选方法,合并两个垂钓行程数组,过滤出和选中ID匹配的条目
import angular from 'angular'; angular.module('plunker', []).controller('MainCtrl', function($scope) { $scope.userInfo = [{"name":"John", "hobby":"fishing", "ID":"123"}, {"name":"Bob", "hobby":"Golf", "ID":"199"}, {"name":"Jerry", "hobby":"Football", "ID":"aAAa"}]; $scope.fishingTrip1 = [{"location":"Alaska", "fisherman":"John", "ID":"123"}, {"location":"Alaska", "fisherman":"Bob", "ID":"144"}, {"location":"Alaska", "fisherman":"Alex", "ID":"161"}]; $scope.fishingTrip2 = [{"location":"Colorado", "fisherman":"Sammy", "ID":"111"}, {"location":"Colorado", "fisherman":"John", "ID":"123"}, {"location":"Colorado", "fisherman":"Jerry", "ID":"aAAa"}]; $scope.selectedID = null; $scope.selectedUser = null; $scope.viewMore = function(ID){ $scope.showDiv = true; $scope.selectedID = ID; // 存储当前选中的用户信息 $scope.selectedUser = $scope.userInfo.find(user => user.ID === ID); }; // 合并两个垂钓行程数组,筛选出匹配当前选中ID的条目 $scope.getMatchedTrips = function() { if (!$scope.selectedID) return []; // 合并两个行程数组 const allTrips = [...$scope.fishingTrip1, ...$scope.fishingTrip2]; // 按ID过滤 return allTrips.filter(trip => trip.ID === $scope.selectedID); } });
2. 调整HTML模板
修改内容如下:
- 给View More按钮传入当前行的用户ID
- 选中用户信息区域仅展示选中的用户,不需要遍历全部用户
- 垂钓行程区域遍历筛选后的匹配行程
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="lib/style.css" /> <script src="lib/script.js"></script> </head> <body ng-app="plunker" ng-cloak> <div ng-controller="MainCtrl"> <h1>Select relevant information from a list</h1><br> <table> <tr> <th>Name</th> <th>ID</th> </tr> <tr ng-repeat = "x in userInfo"> <td>{{x.name}}</td> <td>{{x.ID}}</td> <!-- 传入当前行的用户ID --> <td><button ng-click = "viewMore(x.ID)">View More</button></td> </tr> </table><br><br> <div ng-show = "showDiv"> <table><h3>Selected Information</h3> <tr> <th>Name (Selection)</th> <th>Hobby (Selection)</th> <th>ID (Selection)</th> </tr> <!-- 仅展示选中的用户,不需要遍历全部 --> <tr> <td>{{selectedUser.name}}</td> <td>{{selectedUser.hobby}}</td> <td>{{selectedUser.ID}}</td> </tr> </table><br><br> <div> <h3>Fishing Trips for selected person:</h3> <!-- 遍历匹配到的行程 --> <div ng-repeat="trip in getMatchedTrips()"> 地点:{{trip.location}},垂钓人:{{trip.fisherman}} </div> </div> </div> </div> </body> </html>
修改完成后即可实现需求:点击对应用户的View More按钮,就会展示该用户的基础信息,以及所有和他ID匹配的垂钓行程。
内容的提问来源于stack exchange,提问作者versb
相关产品推荐
相关产品推荐

