DeLe
DeLe

Reputation: 2480

AngularJS - Loop data with dynamic total number

I try to create a input number that provided total number for loop my span tag like

<div ng-app='myApp' ng-controller="myCtrl">
    <input type="number" ng-model="number"> 
    <li ng-repeat="n in [] | range:{{number}}"><span class="glyphicon glyphicon-star" >{{n}}</span></li>
</div>

And here is my JS

var app = angular.module('myApp', []);

function myCtrl($scope){
}    

app.filter('range', function() {
  return function(val, range) {
    range = parseInt(range);
    for (var i=0; i<range; i++)
      val.push(i);
    return val;
  };
});

But that's not working. How to do that thanks

Upvotes: 2

Views: 1005

Answers (2)

Aditya Singh
Aditya Singh

Reputation: 16710

Replace the expression {{number}} with the model number in the range filter. Updated code:

<div ng-app='myApp' ng-controller="myCtrl">
    <input type="number" ng-model="number"> 
    <li ng-repeat="n in [] | range: number"><span class="glyphicon glyphicon-star" >{{n}}</span></li>
</div>

Upvotes: 1

ryeballar
ryeballar

Reputation: 30118

You don't have to interpolate {{number}} inside the ng-repeat directive, you can directly use it as it is.

change:

<div ng-app='myApp' ng-controller="myCtrl">
    <input type="number" ng-model="number"> 
    <li ng-repeat="n in [] | range:{{number}}"><span class="glyphicon glyphicon-star" >{{n}}</span></li>
</div>

to:

<div ng-app='myApp' ng-controller="myCtrl">
    <input type="number" ng-model="number"> 
    <li ng-repeat="n in [] | range:number"><span class="glyphicon glyphicon-star" >{{n}}</span></li>
</div>

Upvotes: 5

Related Questions