AngularJS合并JSON对象后,无法按客户关联展示对应服务器数据
解决AngularJS中客户与对应服务器数据关联展示的问题
我明白你现在的困扰:把客户列表和服务器数据分开存放在customerObject的两个元素里后,遍历客户列表时没法正确对应到每个客户的服务器数据,导致所有客户显示的服务器信息都一样。我们可以通过重新组织数据结构和修改ng-repeat逻辑来解决这个问题。
第一步:重构数据,让客户和服务器数据一一关联
你原来的JavaScript代码在合并数据时逻辑有点混乱,push.apply的用法也不对。我们可以把客户列表和对应的服务器数据整合成一个包含关联信息的数组,这样后续遍历会更方便:
// 先从接口结果中提取客户列表和服务器映射对象 const customerNames = result['customers']; const serverDataMap = result['servers_to_monitor']; // 构建新的数组,每个元素包含客户名和对应的服务器数组 $scope.customerList = customerNames.map(customerName => { return { name: customerName, // 根据客户名从映射对象中取出对应的服务器数据,没有的话返回空数组避免报错 servers: serverDataMap[customerName] || [] }; }); console.log($scope.customerList); // 现在每个元素都有name和servers属性
这样处理后,$scope.customerList里的每一项都是一个完整的客户对象,包含了该客户的名称和对应的所有服务器数据,后续遍历的时候就能直接拿到对应的数据了。
第二步:修改HTML模板,正确遍历关联数据
接下来修改你的AngularJS模板,把原来遍历customerObject[0]改成遍历新的customerList,并且嵌套遍历每个客户的服务器数据:
<div ng-repeat="customer in customerList" class="{{css}}" style="border-radius: 15px"> <!-- 修正了ng class的拼写错误,应该是ng-class --> <div style="float: left; border-radius: 15px !important;" id="{{customer.name}}" ng-class="google_maps"></div> <div style="position: absolute; top: 15px;"> <div class="pull-right mapsLegenda" id="mapsRedBox"> <h1 id="header_{{makeIdPickable(customer.name)}}" class="pull-left mapsTotal" style=" font-size: x-large !important; color: white ;"> {{customer.name}}: {{totals[$index]}} </h1> <br> <!-- 嵌套ng-repeat遍历当前客户的服务器数组 --> <ul ng-repeat="server in customer.servers"> <li> <div class="mapsColor"> <!-- 动态获取当前服务器的名称 --> <p class="mapsColor">{{server.servername}}</p> <!-- 显示当前服务器的颜色 --> <div class="color-box" style="background-color: #{{server.icon_color}}; display: block; width: 10px; height: 10px"></div> </div> </li> </ul> </div> </div> </div>
关键修改点说明:
- 把
ng-repeat="row in customerObject[0]"改成ng-repeat="customer in customerList",这样每次遍历的是包含客户名和服务器数据的完整对象 - 修正了模板里的
ng class拼写错误,正确写法是ng-class - 用嵌套的
ng-repeat="server in customer.servers"来遍历当前客户的所有服务器,确保每个客户只显示自己的服务器数据 - 把原来硬编码的
customerObject[1].customername[0]['servername']改成server.servername,动态获取当前服务器的名称,解决了所有客户显示相同服务器数据的问题
这样修改后,每个客户条目都会正确展示自己对应的服务器列表,再也不会出现数据不匹配的情况啦!
内容的提问来源于stack exchange,提问作者TerranGaming
相关产品推荐
相关产品推荐

