0

I have a json file like this:

[
  {
    "id": "1",
    "name": "John",
    "country": "Philippines"
  },

  {
    "id": "2",
    "name": "Marsha",
    "country": "Philippines"
  },
  {
   "id": "3",
    "name": "Peter",
    "country": "Philippines"
  },
  {
    "id": "4",
    "name": "Kang",
    "country": "Philippines"
  }
]

What I want is to display it in using ng-repeat but since all the countries are the same, I want to display the country only once. How can I possibly do that? My html file is like:

<div ng-repeat="item in citizens">
    <label class="col-md-4 control-label" ng-model="item.id">
        {{item.id}}
    </label>
     <label class="col-md-4 control-label" ng-model="item.name">
        {{item.name}}
    </label>
     <label class="col-md-4 control-label" ng-model="item.country">
        {{item.country}}
    </label>
</div>

Thanks for any help.

bleyk
  • 799
  • 3
  • 14
  • 41

3 Answers3

1

Try changing the label as the following:

<label class="col-md-4 control-label" ng-model="item.country" ng-show="$index>0 && item.country!=citizens[$index-1].country">
    {{item.country}}
</label>

The ng-show will check if the previous item's country is not same as the current item's country , then only show the label. Note : $index>0 will make sure the first item is skipped for this check.

Rambler
  • 4,994
  • 2
  • 20
  • 27
0

Add ng-if condition on the label where we display country name.

   <label class="col-md-4 control-label" ng-bind = "item.country" 
   ng-model="item.country" ng-if="$index>0 && item.country!=citizens[$index-1].country">
  </label>

here is the plunker example

GANI
  • 2,013
  • 4
  • 35
  • 69
  • Thanks for this plunker but it did not display the "Philippines" I need to display the value of the country once since they are all from the same country – bleyk Sep 29 '16 at 07:34
  • Its still the same. It's not displaying the country "Philippines" once as a header – bleyk Sep 30 '16 at 02:31
0

In order to achieve the requirement you have to use the group by filter in angular ng-repeat.

I have attached the code snipped along with

<div ng-repeat="(key, value) in citizens | groupBy: 'country'">
    Group name: {{ key }}
    <div ng-repeat="item in value">
        <div>Name: {{ item.name }}</div>
    </div>
</div>

You have to include angular filter file in your script as well.

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

Also inject the angular filter dependency in your ass like this

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

I think this is what you are looking for. Please look at this for further details

Community
  • 1
  • 1
Nitheesh
  • 19,238
  • 3
  • 22
  • 49