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);
};
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 ? 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With