OdeToCode IC Logo

Group and Display Data with Underscore and AngularJS

Thursday, August 8, 2013

Let’s use the following data to simulate information you might receive from an HTTP API:

$scope.data =
[
    { department: "engineering", name: "Scott" },
    { department: "engineering", name: "Joy" },
    { department: "sales", name: "Sara" }
];

Using underscore.js, it is easy to group the objects by their department attribute.

$scope.groups = _.groupBy($scope.data, "department");

Now $scope.groups will look like the following:

{"engineering":
   [{"department":"engineering","name":"Scott"},
    {"department":"engineering","name":"Sally"}],
 "sales":
   [{"department":"sales","name":"Fred"}]
}

One way to get the data onto the screen is to use an ngRepeater, but the most popular expression form for the repeater (”variable in expression”) doesn’t exactly give us what we want.

<div data-ng-repeat="department in groups">
    <h4>{{ department }}</h4>        
    <ul>
        <li data-ng-repeat="employee in department">
            {{ employee.name }}
        </li>
    </ul>
</div>

That’s because department will hold each value of the groups collection.

image

What we really want is the lesser known expression supported by Angular: (key, value) in expression.

<div data-ng-repeat="(department, employees) in groups">
    <h2>{{department}}</h2>        
    <ul>
        <li data-ng-repeat="employee in employees">
            {{ employee.name }}
        </li>
    </ul>
</div>

Which gives us:

image

As always, there are 101 ways to achieve this end result, but I rather like the (key, value) expressions myself.