AngularJS For Loop with Numbers & Ranges

后端 未结 24 3111
抹茶落季
抹茶落季 2020-11-22 13:40

Angular does provide some support for a for loop using numbers within its HTML directives:

do something <
相关标签:
24条回答
  • 2020-11-22 14:16

    I tried the following and it worked just fine for me:

    <md-radio-button ng-repeat="position in formInput.arrayOfChoices.slice(0,6)" value="{{position}}">{{position}}</md-radio-button>
    

    Angular 1.3.6

    0 讨论(0)
  • 2020-11-22 14:20

    Shortest answer: 2 lines of code

    JS (in your AngularJS controller)

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

    HTML

    <div data-ng-repeat="i in range.slice(0,myCount) track by $index"></div>
    

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

    You can use $index for any tracking operations. E.g. if you want to print some mutation on the index, you might put the following in the div:

    {{ ($index + 1) * 0.5 }}
    
    0 讨论(0)
  • 2020-11-22 14:21

    I came up with an even simpler version, for creating a range between two defined numbers, eg. 5 to 15

    See demo on JSFiddle

    HTML:

    <ul>
        <li ng-repeat="n in range(5,15)">Number {{n}}</li>
    </ul>
    

    Controller:

    $scope.range = function(min, max, step) {
        step = step || 1;
        var input = [];
        for (var i = min; i <= max; i += step) {
            input.push(i);
        }
        return input;
    };
    
    0 讨论(0)
  • 2020-11-22 14:23

    Nothing but plain Javascript (you don't even need a controller):

    <div ng-repeat="n in [].constructor(10) track by $index">
        {{ $index }}
    </div>
    

    Very useful when mockuping

    0 讨论(0)
  • 2020-11-22 14:23

    You can use 'after' or 'before' filters in angular.filter module (https://github.com/a8m/angular-filter)

    $scope.list = [1,2,3,4,5,6,7,8,9,10]
    

    HTML:

    <li ng-repeat="i in list | after:4">
      {{ i }}
    </li>
    

    result: 5, 6, 7, 8, 9, 10

    0 讨论(0)
  • 2020-11-22 14:25

    Hi you can achieve this using pure html using AngularJS (NO Directive is required!)

    <div ng-app="myapp" ng-controller="YourCtrl" ng-init="x=[5];">
      <div ng-if="i>0" ng-repeat="i in x">
        <!-- this content will repeat for 5 times. -->
        <table class="table table-striped">
          <tr ng-repeat="person in people">
             <td>{{ person.first + ' ' + person.last }}</td>
          </tr>
        </table>
        <p ng-init="x.push(i-1)"></p>
      </div>
    </div>
    
    0 讨论(0)
提交回复
热议问题