1

I need to display something x times in the row, but there is no do(x times) in Angular, nor I would like to use additional functions in my controller.

Knowing that

?Array.from({length:5})
(5) [undefined, undefined, undefined, undefined, undefined]

Is it possible make the following code work without adding additional functions or filters in the controller (without using a controller at all).

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app>
  [1,2] - OK:
  <div ng-repeat="x in [1,2]">
    > {{x}}
  </div>

  Array.from({length:5}) - NOK:
  <div ng-repeat="x in Array.from({length:5})">
    > {{x}}
  </div>
</div>

PS

I don't want to display numbers, I just need to display 5 >

PPS.

Practical need:
I need to display the last page of a paginated table, have "availableRowsNumber" and "itemsPerPage", so I need to complete with empty rows, to display the "standard height":

<div ng-repeat="x in Array.from({length:itemsPerPage-itemsPerPage%availableRowsNumber})">
    <tr></tr>
</div>
3
  • 1
    ng-if="$index < 5" Commented Jul 31, 2017 at 12:24
  • Why wouldn't you like to add functions in your controller? And if you only need to display 5, why do you need an ng-repeat? Commented Jul 31, 2017 at 12:26
  • @MikeFeltman I don't have an initial array. Commented Jul 31, 2017 at 12:31

2 Answers 2

2

You can use .constructor

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app>
  <div ng-repeat="x in [].constructor(5) track by $index">
     <span>something that you want to display</span>
  </div>
</div>

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

4 Comments

good solution! remark that without track by does not work! ...do you have an explanation why Array.from({length:5}) doesn't work?
The Array.from() method creates a new Array instance from an array-like or iterable object. So basically you need something to base it on.
I don't think I understand your last comment... as I mention in OP, I have a [undefined,undefined,undefined,undefined,undefined] array via Array.from({length:5})... it should iterate on it, isn't it?
Maybe angular might not be able to render it from the view. I am not sure about the Array keyword.
0

You could use the ng-if like Mike had mentioned:

<div ng-repeat="item in items track by $index" ng-if="$index < 5">
</div>

You could also use limitTo:

<div ng-repeat="item in items | limitTo: 5 track by $index">
</div>

1 Comment

This is not what OP asks. The question is how to do an ng-repeat n times, without having a predefined array and touching a controller or filter

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.