Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-if not comparing $index in ng-repeat

In my code I want to print only first word from the array, and I am using ng-if condition.

HTML:

<div ng-controller="MyCtrl">
  <div ng-repeat="Word in Words">
   <div ng-if="$index === 0" class="preview">{{Word}}- {{$index}}</div>
  </div>
</div>

Controller:

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

function MyCtrl($scope) {
    $scope.Words = ['Mon','Tue','Wed'];
}

As you can see I use ng-if="$index === 0" then print div value but it want work, don't know why?

Example:http://jsfiddle.net/kevalbhatt18/twvy0j4a/3/

like image 801
Keval Bhatt Avatar asked Jan 17 '26 06:01

Keval Bhatt


2 Answers

ngIf comes from angular verison 1.2.1 but you used 1.0.3 So your ng-if is not worked. If you upgrade the angular version to latest it works charmly.

Otherwise my suggestion to use ngShow directive

Use ng-show in this context and simply use $first for show first element in the array

 <div ng-show="$first" class="preview">{{Word}}- {{$index}}</div>

Fiddle

When we use ngIf and ngShow:

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute

like image 180
Sudharsan S Avatar answered Jan 19 '26 20:01

Sudharsan S


An even better way would be to use $first instead of comparing $index

<div ng-controller="MyCtrl">
    <div ng-repeat="Word in Words">
        <div ng-show="$first" class="preview">{{Word}}- {{$index}}</div>
    </div>
</div>
like image 32
pgrodrigues Avatar answered Jan 19 '26 20:01

pgrodrigues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!