user1469734
user1469734

Reputation: 801

Angular GroupBy using without ng-repeat

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.

Upvotes: 0

Views: 153

Answers (1)

Mike Quinlan
Mike Quinlan

Reputation: 2882

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

Upvotes: 1

Related Questions