2

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?

1

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

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>

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.