samstokes / ng-group

Angular.js filter for grouping items by a field.
MIT License
18 stars 8 forks source link

ng-group

An Angular.js filter for grouping items in an array by one of their fields.

Build status

Usage

The package ng-group provides a filter named groupBy for use with ng-repeat.

Example

Say you have an array of objects representing people:

$scope.people = [
  {name: "Frodo Baggins", home: "The Shire"},
  {name: "Samwise Gamgee", home: "The Shire"},
  {name: "Aragorn", home: "Gondor"},
  {name: "Legolas", home: "Mirkwood"},
  /* ... */
];

and you want to display them arranged according to the place they call home:

The Shire

  • Frodo Baggins
  • Samwise Gamgee

Gondor

  • Aragorn

Mirkwood

  • Legolas

Applying the groupBy:'home' filter to people produces an array of places and the people who live there. You can loop through the places with ng-repeat, then loop through the people for a given place with another, nested ng-repeat, like this:

<div ng-repeat="placePeople in people | groupBy:'home':'peopleByHome'">
  <h3>{{placePeople.home}}</h3>
  <ul>
    <li ng-repeat="person in placePeople.items">{{person.name}}</li>
  </ul>
</div>

Angular's two-way data-binding will work as normal. If you remove an item from the array, it will be removed from the view; if it was the only item in its group, the group will be removed as well.

See a working, editable version of the above example on CodePen.

Installing

  1. Add ngGroup.js to your app:

  2. Load ngGroup.js via a script tag. N.B. it must be loaded after Angular.js, but before your app code.

    <script src="https://github.com/samstokes/ng-group/raw/master/path/to/angular.js"></script>
    <script src="https://github.com/samstokes/ng-group/raw/master/path/to/ngGroup.js"></script> <!-- add this -->
    <script src="https://github.com/samstokes/ng-group/raw/master/YourApp.js"></script>
  3. Add the ng.group module to your app's dependencies:

    var app = angular.module('YourApp', [
        'ng.group'                             // add this
    ]);
    
    app.controller('YourCtrl', function () {
      // ...
    });
  4. Now you can use the groupBy filter in your views:

    <div ng-repeat="placePeople in people | groupBy:'home':'peopleByHome'">
      <!-- ... -->
    </div>

Details

Reporting issues

If you have any problems using this, please submit an issue on Github and I will try to help.

Developing

Pull requests and constructive criticism gratefully accepted.

To hack on this, you'll need npm, bower and grunt. Then:

  1. npm install
  2. bower install
  3. grunt – this will:

I'll be more likely to accept a pull request that includes tests :)

Author

Sam Stokes

License

See LICENSE file.