Search code examples
angularjshtml-tableangularjs-ng-repeatng-bind

AngularJS table interface


I am trying to find the best way to display tabular data using AngularJS based on three RESTful data endpoints. For example, the data is comprised of three models:

Roommate

id
name

Chore

id
name

ChoreAssignment

id
day
roommate (fk)
chore (fk)

I want to display the Chore Assignments in a table with day on the x-axis and roommates on the y-axis.

          Mon       Tue       Wed       Thu        Fri       Sat       Sun
Bob       dishes                        mow grass                      dishes
Alice               trash     dishes                         sweep
Mike                                               dishes    vacuum

I can easily display the data in separate lists with ng-repeat but I am unsure about combining them in the table. I am trying to avoid a custom API call for this table specifically if I can simply build it from the three separate lists of data I already have. Any advice is greatly appreciated.


Solution

  • I opted to build a $scope.choreTable object in the controller (utilizing Underscore.js). $q.all() is used to ensure the data promises are all resolved before building the table.

    $q.all([roommateQuery, choreQuery, choreAssignmentQuery]).then(function(){
        $scope.choreTable = [];
        var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    
        _.each($scope.roommates, function(roommate, i){
            $scope.choreTable.push({roommate: roommate, days: []});
            _.each(days, function(day, j){
                $scope.choreTable[i].days.push(
                    _.where($scope.choreAssignments, {roommate: roommate.id, day: day})
                );
            });
        });
    });
    

    resulting in an object like so:

    [
        {
            roommate: {id: 1, name: "Bob"}, 
            days: [[ChoreAssignment1], [], [], [ChoreAssignment2], [], [], [ChoreAssignment1]]
        },
        {
            roommate: {id: 2, name: "Alice"}, 
            days: [[], [ChoreAssignment3], [ChoreAssignment1], [], [], [ChoreAssignment4], []]
        },
        {
            roommate: {id: 3, name: "Mike"}, 
            days: [[], [], [], [], [ChoreAssignment1], [ChoreAssignment5], []]
        }
    ]
    

    and then in the view:

    <tr ng-repeat="row in choreTable">
        <td>
            [[ row.roommate.name ]]
        </td>
        <td ng-repeat="day in row.days">
            <div ng-repeat="choreAssignment in day">
                [[ choreAssignment.chore.name ]]
            </div>
        </td>
    </tr>