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:


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>        
        <li data-ng-repeat="employee in department">
            {{ employee.name }}

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


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

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

Which gives us:


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