2

I have a scenario in application, where i have to run the loop (ng-repeat) no of times based on a parameter set. For Example:-

 $scope.rating = 3;

then run the loop (using ng-repeat) for 3 times.

Raj Rj
  • 3,497
  • 4
  • 24
  • 34
  • ng-repeat works with the item collection.. can you please provide the same.. we can put the condition like ng-if=$index<$scope.val to restrict the iteration. – Nimesh.Nim Feb 10 '16 at 05:45
  • @NimeshKumar The situation is like, based on a integer value I hve to generate html input tag – Raj Rj Feb 10 '16 at 05:48
  • 2
    duplicate of http://stackoverflow.com/questions/16824853/way-to-ng-repeat-defined-number-of-times-instead-of-repeating-over-array – Narendra CM Feb 10 '16 at 05:56
  • got it.. solution already there @ http://stackoverflow.com/questions/16824853/way-to-ng-repeat-defined-number-of-times-instead-of-repeating-over-array – Raj Rj Feb 10 '16 at 07:16
  • answer to this question is available @ http://stackoverflow.com/questions/16824853/way-to-ng-repeat-defined-number-of-times-instead-of-repeating-over-array – Raj Rj Feb 10 '16 at 07:17

3 Answers3

1

Below will the code in your controller..

$scope.rating = 3;
$scope.getRating = function(rate) {
    return new Array(rate);   
}

Below will be your template.

  <div ng-repeat="i in getRating(rating) track by $index">
    <input type="text" name="txt" value="{{$index}}"/>
 </div>
Nimesh.Nim
  • 388
  • 2
  • 9
  • Sorry!! Not working. Based on a integer value I have to generate input fields. IF a = 5 then generate 5 input fields. – Raj Rj Feb 10 '16 at 07:01
  • 1
    i am setting your integer value to $scope.rating and it is generating 3 textboxes. – Nimesh.Nim Feb 10 '16 at 07:15
1

I think this is cleaner and shorter way

var app = angular.module('app', []);
 
    app.controller('Ctrl', function($scope) {

      $scope.counter = 2; 
      $scope.generateFields = function(count) {
       return new Array(count);   
      }
     

    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
   
  Insert Number To Generate Fields:
  <input type='number' ng-model='counter'/>
  <hr>
  <div ng-repeat="i in generateFields(counter) track by $index">
    <input type="text" name="txt" value="Input Field {{$index}}"/>
 </div>
</div>
Zeeshan Hassan Memon
  • 8,105
  • 4
  • 43
  • 57
0

You can do it by nested ng-repeat using like this :

In controller

var rating = [3];
//u can set it dynamically too {var rating = [req.body.rating]}
//erq.body.rating is getting value from text/input box
$scope.rating = rating;

In HTML

<div ng-repeat = i in rating>
  <div ng-repeat = ____></div>  // this ng-repeat will run based on rating value
</div>
Amulya Kashyap
  • 2,333
  • 17
  • 25