2
<select>
<option>1</option>
<option selected>2</option>
<option>3</option>
</select>

Says I have 3 qty in my json, I know can using loop using jquery but how do I build my html using ng-repeat of angular? since it doesn't have [1,2,3] but just 3.

http://jsfiddle.net/qpLuw80j/ Added jsfiddle to example my case clearer.

Cody Jonas
  • 151
  • 6

4 Answers4

0

put your ng-repeat inside the option tag option ng-repeat="value in values"

{{value.name}}

/option

then remove the rest of your option

dione llorera
  • 357
  • 4
  • 14
0

You can use this filter:

check your code here: http://jsfiddle.net/qpLuw80j/2/

Filter defined as:

var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=1; i<=total; i++) {
      input.push(i);
    }

    return input;
  };
});

With the repeat used like this:

<div ng-repeat="n in [] | range:100">
  do something
</div>

Your Code:

HTML:

<div ng-app='app' ng-controller='mainCtrl'>
    <div ng-repeat="json in myJson">
        <li>{{json.name}}</li>
        <select>
        <option ng-repeat="n in [] | range:json.qty" ng-bind="n"></option>
        </select>
    </div>

JS:

var  angular = angular.module('app',['QuickList']);
angular.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=1; i<=total; i++) {
      input.push(i);
    }

    return input;
  };
});
angular.controller('mainCtrl', function($scope){
    $scope.myJson = [
  {
    "id": "1",
    "name": "banana",
    "price": 12,
    "qty": 3,
  },
  {
    "id": "2",
    "name": "watermelon",
    "price": 12.9,
    "qty": 4,
  }
]

})
Alvaro Silvino
  • 9,441
  • 12
  • 52
  • 80
0

I've added a function on your fiddle to create a range for your quantity:

$scope.range = function(min, max, step) {
    step = step || 1;
    var input = [];
    for (var i = min; i <= max; i += step) {
        input.push(i);
    }
    return input;
};

I got the range function from here: https://stackoverflow.com/a/17124017/1015690

Then, I used this function on ng-repeat for your options:

<option ng-repeat="n in range(1,json.qty)">{{n}}</option>

...and here is your updated fiddle: http://jsfiddle.net/qpLuw80j/1/

:D

Community
  • 1
  • 1
Diego Polido Santana
  • 1,425
  • 11
  • 19
0

You could use map to add an array to each item of your initial array:

 $scope.myJson.map(function(item) {
    item.qtyArray = [];
    for (var i = 1; i <= item.qty; i++) {
      item.qtyArray.push(i);
    }
    return item;
  })

and then

<select ng-options="item for item in json.qtyArray" ng-model="selected"> </select>

Here is the updated fiddle.

Lulylulu
  • 1,254
  • 8
  • 17