mpsbhat mpsbhat - 4 months ago 19
Javascript Question

nested list based on type column in angularjs

I have an angularjs sample here where it contains a sample array

$scope.myarr = [
{id: 1, name: 'foo',type: 1},
{id: 2,name: 'bar',type: 1},
{id: 3,name: 'quad',type: 2},
{id: 4,name: 'cab',type: 2},
{id: 5,name: 'baz',type: 2},
{id: 6,name: 'cad',type: 3}
];


Myself trying to create a list using
ng-repeat
and it can be done as

<ul ng-repeat="x in myarr">
<li>{{x.id}}. {{x.name}} - Type {{x.type}}</li>
</ul>


But actually what is wanted is a nested list based on
x.type
column as,


  1. Type 1

    • 1. foo

    • 2. bar



  2. Type 2

    • 3. quad

    • 4. cab

    • 5. baz



  3. Type 3

    • 6. cad





How can it be done using angularjs?

Answer

Making use of a inner ng-repeat and filter / unique

AngularJS doesn't include a unique filter by default. You can use the one from angular-filter. Just include the JavaScript

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>

and include the dependeny in your app:

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

More information on https://docs.angularjs.org/api/ng/directive/ngRepeat

<div id="app" ng-app="myApp" ng-controller="myCtrl">
  <ul ng-repeat="x in myarr | unique:'type'">
      <li>{{x.id}}. {{x.name}} - Type {{x.type}}</li>
      <ul>
        <li ng-repeat="y in myarr | filter:type=x.id"> 
          {{y.name}}
        </li>   
      </ul>
  </ul>
</div>

angular.module('myApp', []).controller('myCtrl', function($scope) {
 $scope.myarr = [
    {id: 1, name: 'foo',type: 1},
    {id: 2,name: 'bar',type: 1},
    {id: 3,name: 'quad',type: 2},
    {id: 4,name: 'cab',type: 2},
    {id: 5,name: 'baz',type: 2},
    {id: 6,name: 'cad',type: 3}
  ];
});

Will give a result of :

Type 1
    1. foo
    2. bar
Type 2
    3. quad
    4. cab
    5. baz
Type 3
    6. cad

See updated Fiddle

Comments