angularjsangularjs-ng-repeatng-showionic-v1

How to create nested structure with ng-repeat in AngularJS


Issue with ng-repeat, AngularJS looping

I'm having trouble creating this loop structure using ng-repeat in angular js(ionic 1 app). When I use ng-repeat, the date is repeatedly shown along with each event in every loop. But I want to show the date only once for corresponding events as shown in the picture.

image


Solution

  • You need a groupBy filter, which you (write manually, or) get from angular-filter module. Simply set a JSON with events and dates listed together. Here is a small demo that you can adjust to your example:

    var app = angular.module('myApp', ['angular.filter']);
    app.controller('myCtrl', function($scope) {
      $scope.events = [{
          "date": "Sept-1",
          "event": "Event 1"
        },
        {
          "date": "Sept-1",
          "event": "Event 2"
        },
        {
          "date": "Sept-2",
          "event": "Event 3"
        },
        {
          "date": "Sept-2",
          "event": "Event 4"
        },
        {
          "date": "Sept-3",
          "event": "Event 5"
        },
      ]
    });
    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.17/angular-filter.min.js"></script>
    
    <body>
    
      <div ng-app="myApp" ng-controller="myCtrl">
    
        <div ng-repeat="(key, value) in events | groupBy: 'date'">
          - {{key}}
          <div ng-repeat="val in value">
            * {{val.event}}
          </div>
          <br>
        </div>
    
      </div>
    
    </body>
    </html>