0

In AngularJS there is the groupBy method for ng-repeats. I'm using that to make a list of times a product with the same title is in the array I'm ng-repeating, and calculate the length and total price of it like this:

<li ng-repeat="(key, value) in products | groupBy: 'title'">
    <span>{{value.length}} items</span>
    <strong>{{ value[0].title }}</strong>

    <tt>{{ (value[0].price*value.length) | currency: '$' }}</tt>
</li>

This works fine, but I wanna re-use that same calculation in the Controller. So I have an object/array like:

{
    {
        length: 10,
        title: 'test 1',
        price_total: 200.99,
    },
    {
        length: 3,
        title: 'test 2',
        price_total: 3.99,
    },
}

But I can't figure out how to use the same GroupBy kinda thing.

user1469734
  • 851
  • 14
  • 50
  • 81
  • 1
    You could use _.groupBy if you have lodash/undescore in your project – xSaber Feb 26 '16 at 23:09
  • maye be this question could be helpful: http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects – dobleUber Feb 26 '16 at 23:16
  • groupby is a filter, you can use filter in controllers, but I do not recommend do it, anyway you can check this post: http://stackoverflow.com/questions/14302267/how-to-use-a-filter-in-a-controller – dobleUber Feb 26 '16 at 23:18

1 Answers1

1

You can inject AnguarJS filters like this:

angular.module('myApp')
  .controller('MyCtrl', function($filter, $scope) {
    $scope.myCollection = [{
      title: 'Wut',
      text: 'Wat'
    }, {
      title: 'Que',
      text: 'paso'
    }]

    $scope.grouped = $filter('groupBy')($scope.myCollection, 'title');
  })

in order to get the same functionality that you would from a directive. Documentation here

Mike Quinlan
  • 2,873
  • 17
  • 25