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:"city",name:"New York"},

The ‘collection’ is array which contains cities and countries.

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

<div ng-repeat="item in collection">

Generate the list of the cities and countries separately- using ng-repeat with condition

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.

  <div ng-repeat="item in collection" ng-if='item.type=="city"'>
  <div ng-repeat="item in collection" ng-if='item.type=="country"'>

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">
    {{}} is in the first position in the list

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.