0

In angular, if i have an object such as :

[{
  id : 1, 
  subject : BIO, 
  class : '101' , 
  time : 'mon'
 },
 {
  id : 2, 
  subject : BIO, 
  class : '101', 
  time : 'tues' 
 },
 { 
  id : 3, 
  subject : MTH, 
  class : '101-00', 
  time : 'wed'
 },
 {
  id : 4, 
  subject : MTH, 
  class : '101',
  time : 'tues'
 },
 {
  id : 5, 
  subject : BIO, 
  class : '102', 
  time : 'sat' 
 },

And I wanted to display all of the results underneath each subject title, is there a directive I can use or something I need to whip up?

Is there way to output based on key value pair by category?

so my output would be


BIO

All class numbers and time.


MTH

All math classes.

2 Answers 2

2

You can use "groupBy" filter from angular-filter library which does exactly what you need: https://github.com/a8m/angular-filter#groupby

Sign up to request clarification or add additional context in comments.

1 Comment

Agree, is cleaner than having 2 separate blocks... The @Claies response will be helpful when you need a certain order to show the blocks.
0

The easiest way to do this would be to use a filter over ng-repeat. Something like the following:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.classes = [{
    id: 1,
    subject: 'BIO',
    class: '101',
    time: 'mon'
  }, {
    id: 2,
    subject: 'BIO',
    class: '101',
    time: 'tues'
  }, {
    id: 3,
    subject: 'MTH',
    class: '101-00',
    time: 'wed'
  }, {
    id: 4,
    subject: 'MTH',
    class: '101',
    time: 'tues'
  }, {
    id: 5,
    subject: 'BIO',
    class: '102',
    time: 'sat'
  }, ]
});
<script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js" data-semver="1.5.10"></script>

<body ng-app="plunker" ng-controller="MainCtrl">
  BIO:
  <div ng-repeat="class in classes | filter: 'BIO'">
    {{class.subject}} {{class.class}} {{class.time}}
  </div>
  <hr> MTH:
  <div ng-repeat="class in classes | filter: 'MTH'">
    {{class.subject}} {{class.class}} {{class.time}}
  </div>
  <hr> ALL:
  <div ng-repeat="class in classes">
    {{class.subject}} {{class.class}} {{class.time}}
  </div>
</body>

http://plnkr.co/edit/AJXZtCHz5ZA51FWIBaXU?p=preview

I added the groupBy filter to the mix to show the difference, from the answer by @DmitryVasiliev

http://plnkr.co/edit/wEEvOfccZ0ipPS14vnD5?p=preview

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.