Shai Kimchi
Shai Kimchi

Reputation: 786

display list from complex json using angular

I have this JSON (I did not create it and can not change it)

{"tags": [
    {
      "title": "news",
      "options": [
          {
            "title": "important",
          },
          {
            "title": "less important",
          }
         ]
    },
    {
       "title": "entertainment",
       "options": [
           {
              "title": "entertainment",
           }
          ]
     }

I would like to display it as a list, where if a certain title hasonly one option then the title should be displayed in the list, and if a title has more than one item in options, then the main title should be displayed and the options titles should also be displayed. the final result (according to the above example) should display:

 <ul>
     <li>news<ul>
                <li>important</li>
                <li>less important</li>
             </ul>
        </li>
    <li>entertainment</li>
  </ul>

how can I do this in angularJS?

Upvotes: 2

Views: 325

Answers (3)

Shai Kimchi
Shai Kimchi

Reputation: 786

Thnx, both above suggestions helped clear out the solution. I needed to nest two ng-repeat loops together and apply an ng-if to the inner loop.

I ended up with this soultion:

<ul> <li ng-repeat="x in myData.tags"> {{x.title}} <ul ng-repeat="y in x.options" ng-if="x.options.length>1"> {{y.title}} </ul> </li> </ul>

Upvotes: 1

Rakesh Chand
Rakesh Chand

Reputation: 3113

I am assuming your json file is stored in a variable called result

<ul ng-repeat = "tg in result.tags">
   <li ng-if="tg.options.length > 1">{{tg.title}}
      <ul ng-repeat ="innerElement in tg.options" >
         <li>{{innerElement.title}}</li>
      </ul>
   </li>
   <li ng-if="tg.options.length==1">{{tg.title}}</li>
</ul>

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You can try with something like that if myList is the name that you use in the $scope for the json object. Basically is an ng-repeat with an inner ng-repeat

<ul ng-repeat="element in myList.tags">
    <li>
        {{element.title}}
        <ul ng-repeat="innerElement in element.options">
            <li>{{innerElement.title}}</li>
        </ul>
     </li> 
</ul>

Upvotes: 3

Related Questions