2

Let's say I have this JSON:

var myObj = {
    {"key1":"value1", "key2":5, "key3":"value3" },
    {"key1":"value4", "key2":2, "key3":"value5" },
    {"key1":"value6", "key2":4, "key3":"value6" },
}

I want to use this for ng-Repeat. But the values of "key2" must iterate within their own ng-repeat. So something like this:

<ul ng-repeat="x in myObj">
   <li> {{x.key1}} </li>
   <ul ng-repeat="y in x.key2">
      <li></li>
   </ul>
   <li> {{x.key3}} </li>
</ul>

Obviously this doesn't work. The result of the first array should like this (5 li-elements should be created):

<ul>
  <li> value1 </li>
  <ul>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
  </ul>
  <li> value 3 </li>
</ul>

2 Answers 2

2

You can create custom method range that on range(n) will return [1,2,3, .. n]

HTML

<div ng-controller="MainCtrl">
 <ul ng-repeat="x in myObj">

   <li> {{x.key1}} </li>
   <ul ng-repeat="y in range(x.key2)">
      <li></li>
   </ul>
   <li> {{x.key3}} </li>
</ul>

JS

 $scope.myObj = [
    {"key1":"value1", "key2":5, "key3":"value3" },
    {"key1":"value4", "key2":2, "key3":"value5" },
    {"key1":"value6", "key2":4, "key3":"value6" },
];


$scope.range = function(count){
  var items = []; 
  for (var i = 0; i < count; i++) { 
    items.push(i) 
  } 

  return items;
}

Demo Plunker

Sign up to request clarification or add additional context in comments.

Comments

0

Add this method in your controller as

 $scope.getNumber = function(count){
      return new Array(count);  
    }

and update your html as

 <ul ng-repeat="x in myObj">
       <li> {{x.key1}} </li>
       <ul ng-repeat="y in getNumber(x.key2)">
          <li></li>
       </ul>
   <li> {{x.key3}} </li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.