AngularJS数据库表动态列展示及数据匹配修正问题
Hi there, let's fix that data misalignment issue you're facing! The problem right now is that your current filter only matches the property name, but it doesn't ensure each value is paired with the correct user from your names array—so the values end up out of order.
Here's a straightforward solution to get your table displaying correctly, even when new names are added dynamically:
Step 1: Add a helper function in your AngularJS controller
First, create a function that will fetch the exact value for a given property and user name. This ensures we're always pulling the right data point:
$scope.getValue = function(property, userName) { // Find the matching record in totalData const matchingRecord = $scope.totalData.find(item => { return item.property === property && item.name === userName; }); // Return the value if found, or an empty string if not return matchingRecord ? matchingRecord.value : ''; };
Step 2: Update your HTML template
Modify the <tbody> section of your table to use this helper function instead of relying solely on filters. This way, each cell will directly map to the correct property-user pair:
<tbody> <tr ng-repeat='p in properties'> <td>{{p}}</td> <!-- Loop through each name in your names array --> <td ng-repeat='name in names'> <!-- Call our helper function to get the right value --> {{getValue(p, name)}} </td> </tr> </tbody>
Why this works
Your original filter filter : {property : p}: true returns all records for a given property, but there's no guarantee those records are ordered the same way as your names array. By using the getValue function, we explicitly look up the value for each property-user combination, eliminating any misalignment.
This approach also scales perfectly when new names are added—since we're dynamically looping through the names array, new columns will automatically appear, and the helper function will still find the correct values for the new users.
Just double-check that your totalData array has objects structured like this (each entry is a property-value-user tuple):
$scope.totalData = [ { property: 'Age', value: '20', name: 'Jack' }, { property: 'Sex', value: 'Male', name: 'Jack' }, { property: 'Diabetic', value: 'Yes', name: 'Jack' }, // ... and so on for Jim, Jessie, and future users ];
内容的提问来源于stack exchange,提问作者Akshay

