Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular repeat <span> n times

Tags:

angularjs

I have a JSON object that contains an int property x, I would like to repeat following code x times

<span class="glyphicon glyphicon-star"/>

ng-repeat does not seem to be indicated as it's working with collection.
Any suggestion (angular newbie)

like image 802
Frederic Close Avatar asked Dec 10 '13 22:12

Frederic Close


People also ask

What is ngRepeat in angular?

Definition and Usage 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 can I use instead of NG-repeat?

The *ngFor directive in Angular is similar to the ng-repeat directive in AngularJS. It repeats the associated DOM element for each item in the specified collection.

How do I get an index value in ng-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.


2 Answers

I would use custom filter with ng-repeat:

HTML

<div ng-app='myApp' ng-controller="Main">
    <li ng-repeat="n in [] | range:20">
      <span class="glyphicon glyphicon-star" >{{n}}</span>
    </li>
</div>

filter

app.filter('range', function() {
  return function(val, range) {
    range = parseInt(range);
    for (var i=0; i<range; i++)
      val.push(i);
    return val;
  };
});

Demo Fiddle

like image 172
Maxim Shoustin Avatar answered Oct 17 '22 07:10

Maxim Shoustin


Shortest answer: 2 lines of code

JS (in your AngularJS controller)

$scope.range = new Array(MAX_STARS); // MAX_STARS should be the most stars you will ever need in a single ng-repeat

HTML

<span class="glyphicon glyphicon-star" ng-repeat="i in range.slice(0,starCount) track by $index"/>

...where starCount is the number of stars that should appear in this location.

like image 24
JellicleCat Avatar answered Oct 17 '22 08:10

JellicleCat