AngularJS groupby or filter a list of objects inside of a service instead of in HTML template?

How can I sort a list of objects:

[
{a: 3, b: "H", c: "A"}
{a: 4, b: "G", c: "B"}}
{a: 1, b: "F", c: "E"}}
{a: 2, b: "E", c: "E"}}
{a: 6, b: "D", c: "D"}}
{a: 5, b: "A", c: "D"}}
]

Using Javascript within angularjs? I know there are directives for inclusion in the HTML to help sort this, but is there I way I can call some function on some $filter or something like that in a Service and/or Controller to sort my object? Say I want to sort by key "a"... or

  • sort by key "a" and filter where key "c" is qual to D.
  • group by "c", aggregate counts in "a"

Or does everything have to work through the html template directives?

You can use $filter service in controllers:

app.controller('MainCtrl', function($scope, $filter) {
  $scope.source = [{
    a: 3,
    b: "H",
    c: "A"
  }, {
    a: 4,
    b: "G",
    c: "B"
  }, {
    a: 1,
    b: "F",
    c: "E"
  }, {
    a: 2,
    b: "E",
    c: "E"
  }, {
    a: 6,
    b: "D",
    c: "D"
  }, {
    a: 5,
    b: "A",
    c: "D"
  }];

  $scope.filtered = $filter('filter')($scope.source, 'D', 'c');

});

This example uses 'filter' filter in AngularJS to find the objects with 'D' value in c property. Here's a working plunk: http://plnkr.co/edit/8kWhtOuSX0iEzuMEQdnq?p=preview

This documentation page gives some more details : https://docs.angularjs.org/guide/filter