Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-repeat with array length condition

I want the ng-repeat to run only when the photos.length > 1

Doing this doesn't seem to work:

<div ng-repeat="thumb in photos | photos.length > 1">

Is there any quick trick / elegant way to do this? I just need to check for array length and nothing else fancy.

I would hate to duplicate the array to another array by doing something like this

if (oldArray.length > 1)
 newArray = photos;
else
 newArray = [];

...and then do ng-repeat on newArray. This seems inefficient.

Thanks.

like image 352
HP. Avatar asked Feb 24 '14 07:02

HP.


People also ask

How do you condition in NG-repeat?

You can add condition using ng-if also and this is effective too. You can apply any condition to your list using ng-if attribute. In below example, I have put condition where Age > 20 and IsActive is true. ng-repeat will fetch all records which full fill this scenario.

What is the use of NG-repeat in angular?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What is $Index in AngularJS?

Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}.


2 Answers

Try:

<div ng-repeat="thumb in photos" ng-if="photos.length > 1"></div>

if the ng-if condition is not satisfied those elements will be removed from the DOM. See http://docs.angularjs.org/api/ng/directive/ngIf for further reference.

like image 71
kamilkp Avatar answered Oct 06 '22 23:10

kamilkp


You could try using the ng -if directive to check the condition you describe e.g.

<div ng-if='photos.length > 1'> your HTML here </div>
like image 36
rom99 Avatar answered Oct 06 '22 23:10

rom99