AngularJS(Ionic)中如何从关联数组取值并在ng-repeat列表展示?
Great question! There are two practical approaches to link your customers and SizeOfCustomers arrays via their shared id and show the size value in your ng-repeat. Let's walk through both:
Approach 1: Use a Helper Function (Quick & Simple)
If your datasets are small, this is a straightforward solution that requires minimal changes to your existing data structure.
Controller Code:
Add a reusable function to fetch the size for a given customer ID:
$scope.getCustomerSize = function(customerId) { // Loop through the size array to find a matching ID for (let i = 0; i < $scope.SizeOfCustomers.length; i++) { if ($scope.SizeOfCustomers[i].id === customerId) { return $scope.SizeOfCustomers[i].size; } } // Return a default value if no match is found return 'Unknown'; };
Template Code:
Call the function directly in your ng-repeat to display the size:
<ion-list> <ion-item ng-repeat="x in customers"> <h2>{{x.name}}</h2> <p>City: {{x.city}}</p> <p>Size: {{getCustomerSize(x.id)}}</p> </ion-item> </ion-list>
Approach 2: Pre-Merge the Arrays (Better Performance)
For larger datasets, pre-merging the arrays into a single collection is more efficient. This avoids repeated function calls during Angular's digest cycles, which can slow down your app.
Controller Code:
First create a lookup map for sizes, then merge it into your customers array:
// Create a map for fast size lookup by ID const sizeLookupMap = {}; $scope.SizeOfCustomers.forEach(sizeItem => { sizeLookupMap[sizeItem.id] = sizeItem.size; }); // Merge size data into each customer object $scope.customers.forEach(customer => { customer.size = sizeLookupMap[customer.id] || 'Unknown'; });
Template Code:
Now you can directly access the size property in your ng-repeat without extra function calls:
<ion-list> <ion-item ng-repeat="x in customers"> <h2>{{x.name}}</h2> <p>City: {{x.city}}</p> <p>Size: {{x.size}}</p> </ion-item> </ion-list>
Which Approach to Pick?
- Go with Approach 1 if your customer list is small (dozens of items max) and you want minimal code changes.
- Choose Approach 2 for larger lists or if performance is a priority, as it processes the data once instead of on every digest cycle.
内容的提问来源于stack exchange,提问作者jane

