Baki
Baki

Reputation: 614

Angular limit to first ng-if TRUE item in ng-repeat

Hej, how do I show only the first number that evaluates to true inside ng-repeat?

In my directive (or controller) I have:

ctrl.things = [1,2,3,4,5,6];

and in my html:

<div ng-repeat='thing in ctrl.things' >
    <span ng-if="thing>3" ng-show="$first">{{thing}}</span>
</div>

How do I display only 4 as a result?

Please bear in mind that this example is simplified. There is actually an ng-repeat inside ng-repeat and because of that (and other things) there are not many things I co do inside the directive (controller). Many thanks for any solution.

Upvotes: 1

Views: 3102

Answers (3)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Declare a method in the scope

$scope.getData=function(obj){
      return obj > 3;
    }

Then add this as filter in div

<div ng-repeat='thing in things | filter : getData'  ng-if="$first"> 
    <span >{{thing}}</span>
</div>

JSFIDDLE

If wanna to use this

Try like this

Declare a method in the scope

vm.getData=function(obj){
  return obj > 3;
}

Then add this as filter in div

 <div ng-repeat='thing in vm.things | filter : vm.getData'  ng-if="$first"> 
    <span >{{thing}}</span>
</div>

JSFIDDLE

Upvotes: 2

Shubham Nigam
Shubham Nigam

Reputation: 3944

I think you are looking for this:

//controller
$scope.ctrl={};
$scope.ctrl.things=[{1:false},{2:false},{3:false},{4:true},{5:true}];
$scope.check=function(value){
 $scope.count = value === true?($scope.count+1):$scope.count;
 return $scope.count ===1 ;
}
//end of controller

HTML

<div ng-repeat='(key,value) in ctrl.things' >
    <span ng-if="check(value)">{{key}}</span>
</div>

To show first element if you want to show last item you can put ng-if="$last"

Upvotes: 0

Vi100
Vi100

Reputation: 4203

You should have to create a filter or inline it like this:

<div ng-repeat='thing in ctrl.things' ng-if="thing > 3">
    <span ng-if="$first">{{thing}}</span>
</div>

That should work

Upvotes: 0

Related Questions