9

Using Angularjs, I want to create say 10 <div> if user inputs '10' in a text box.

<input type="text" id="gcols" placeholder="Number of Columns" ng-model="cols"/>

So whatever value user enters in this box, those many shall be created. So my generalized question is, how to 'ng-repeat' a <div> for 'ng-model' times?

UPDATE: Appreciating for all of your answers, I did something like following, by referring your answers. And that is working as of now, but tell me if any other logic is more efficient than this.

$scope.divs = new Array();

    $scope.create=function(){ //I added a button & invoked this function on its ng-click
            var a = $scope.cols;
            for(i=0;i<a;i++)
            {
                $scope.divs.push(a);
            }
            alert($scope.divs);
        };
Sujit Y. Kulkarni
  • 1,186
  • 3
  • 22
  • 37
  • possible duplicate of [ng-repeat defined number of times instead of repeating over array?](http://stackoverflow.com/questions/16824853/ng-repeat-defined-number-of-times-instead-of-repeating-over-array) – Stewie Jan 02 '14 at 12:04

3 Answers3

12

You need to create an array to iterate on it. In your controller:

app.controller('ctrl', function ($scope) {
    $scope.cols = 0;
    $scope.arr = [];
    $scope.makeArray = function () {
        $scope.arr.length = 0;
        for (var i = 0; i < parseInt($scope.cols) ; i++) {
            $scope.arr.push(i);
        }
    }
});

In your view:

<div ng-controller="ctrl">
    <input ng-model="cols" type="text" ng-change="makeArray()" />
    <div ng-repeat="o in arr">hi</div>
</div>

JSFiddle

Alborz
  • 6,843
  • 3
  • 22
  • 37
6

DEMO: http://jsfiddle.net/JsFUW/

In your module/app/controller

$scope.cols =4; /* a default */
$scope.divs =[]; /* whatever these are */

In the template

<input type="text" id="gcols" placeholder="Number of Columns" ng-model="cols"/>

  <div ng-repeat="div in divs | limitTo:cols" >
    ... 
  </div>

As comment question , try this :

In the controller

  $scope.cols

In the template

 <input type="text" id="gcols" placeholder="Number of Columns" ng-model="cols"/>

 <h3>cols: {{cols}} </h3>

Do you see that value change on the page as you type ? If not your $scope.cols is not in the template scope.

Rob Sedgwick
  • 5,216
  • 4
  • 20
  • 36
1

In your view:

<input ng-model="cols" ng-change="colsChanged()"/>

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

In your controller:

app.controller('MyCtrl', function($scope) {
  $scope.cols = 0;
  $scope.colsChanged = function () {
     $scope.items = new Array(+$scope.cols);
  };

  //optional: if you're starting with 1 or more "cols"
  $scope.colsChanged();
});

Alternatively, you could roll your own directive that used transclusion to repeat itself multiple times, but that could get involved and probably isn't going to gain you much.

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232