Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - How to 'ng-repeat' a div for 'value in ng-model'-times?

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);
        };
like image 315
Sujit Y. Kulkarni Avatar asked Jan 02 '14 11:01

Sujit Y. Kulkarni


People also ask

What is ng-repeat in Angular 2?

The ng-repeat is a directive which is used to repeat or to generate a tag (or) element multiple times (based on the count of our array size or collection). This is will be similar to the foreach loop which loops throughout the whole collection. //we can use “item” to get the value from collection each time it loops.

How to filter ng-repeat values according to nG-model using AngularJS?

How to filter ng-repeat values according to ng-model using AngularJS ? The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

How do I display repeating values in an angular controller?

Angular provides a directive called "ng-repeat" which can be used to display repeating values defined in our controller. Let's look at an example of how we can achieve this.

What is ng-repeat in jQuery?

The ng-repeat is a directive which is used to repeat or to generate a tag (or) element multiple times (based on the count of our array size or collection). This is will be similar to the foreach loop which loops throughout the whole collection.


1 Answers

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

like image 77
Alborz Avatar answered Nov 10 '22 00:11

Alborz