angularjs

AngularJS: Using if condition in ngRepeat directive

You know that you can apply the iteration on any html template using the ngRepeat over the collection. Let’s suppose that you have the collection of the city and countries name then you can generate the html template for each item in the collection.

I am trying to demonstrate you how can you do it. Let’s suppose you have the following collection of the items:

  $scope.collection = [
        {type:"city",name:"New Delhi"},
        {type:"country",name:"India"},
        {type:"country",name:"USA"},
        {type:"city",name:"New York"},
        {type:"country",namename:"Japan"},
        {type:"city",name:"Tokyo"},
        {type:"city",name:"Paris"}
    ];

The example below shows use the ngRepeat to show all items in the list:

<div ng-repeat="item in collection">
{{item}}
</div>

Generate the list of the cities and countries separately
The ngIf directive removes a portion of the DOM tree based on the given expression. If the expression evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
In the below first ngIf expression check the type of the item to city, if item type is ‘city’, the div element insert with the city name into the DOM. Similarly in the second ngIf expression contains the check for the country.

<h3>Cities</h3> 
  <div ng-repeat="item in collection" ng-if='item.type=="city"'>
    {{item.name}}
  </div>
  <h3>Countries</h3>
  <div ng-repeat="item in collection" ng-if='item.type=="country"'>
    {{item.name}}
  </div>

In the below image you can see the result:
ng-if in ng-repeat in angularjs

Identify the first iteration and last iteration in the ngRepeat

There are several properties which you can use with the ngRepeat directive: $index,$first, $middle,$last,$even and $odd. Read ‘More on ngRepeat‘.

Use the $first with ngIf:

  <div ng-repeat="item in collection" ng-if="$first">
    {{item.name}} is in the first position in the list
  </div>

The output will be:


New Delhi is in the first position in the list

Thank you, let me know if you need more clarification or the examples.