1

I am trying to iterate over an array using ng-repeat to display in a list. The number of records to display should be equal to the length of a second array.

 <ul>
  <li ng-repeat="item in firstArray"></li>
 </ul>

 var firstArray = ["a","b","c","d","e","f"]
 var secondArray = ["x","y","z"]

The expected result for the above example :

 var output = ["a","b","c"]

Since the length of secondArray is 3, the number of li elements would be 3 with the first three values from firstArray.

Should i use filter? I am using angularjs.

Thanks

5 Answers 5

5

The simplest solution is to use limitTo

<ul>
  <li ng-repeat="item in firstArray | limitTo:secondArray.length">{{item}}</li>
</ul>

http://plnkr.co/edit/LWh1uqNPxTy09u3MP677?p=preview

Sign up to request clarification or add additional context in comments.

Comments

1
<ul>
  <li ng-repeat="item in firstArray" ng-if=" $index < secondArray.length "></li>
</ul>

Use the above code, it will work

1 Comment

That's performance unwise, instead of rendering only required number of elements you will create multiple watchers with ngIf to compare $index and array length in every $digest cycle
1

You can use AngularJs filter limitTo in ng-repeat. Refer to the below example:

At angular application side:

    var app = angular.module('sampleapp', [])
    app.controller('samplecontrol', function ($scope) {
        $scope.firstArray = ["a","b","c","d","e","f"]
        $scope.secondArray = ["x","y","z"]
    });

In your view:

<ul>
    <li ng-repeat="item in firstArray | limitTo:secondArray.length">{{item}}</li>
</ul>

Comments

0

Maybe you should use $index to test if it has to be displayed :

<ul >
     <li ng-repeat="item in firstArray" ng-if="$index < secondArray.length()" > </li>
 </ul>

Comments

0

Just loop over your second array and access the items of the first array using firstArray[$index].

angular.module('myApp', [])
.controller('myCtrl', function ($scope) {
	$scope.firstArray = ["a","b","c","d","e","f"];
    $scope.secondArray = ["x","y","z"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="myCtrl">
        <ul>
            <li ng-repeat="i in secondArray">
                {{firstArray[$index]}}
            </li>
        </ul>
    </div>
</div>

1 Comment

And on the way access not existing element of first array and produce way to many li that's needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.