0

I'm trying to iterate over a given JSONObject, which contains JSONArray in it and display it in html. So, here is the example:

jsonData:

{
    "category1": [
        {
            "name": "Some title",
            "desc": "And its description"
        },
        {
            "name": "Another title here",
            "desc": "Also description here"
        }
    ],
    "category2": [
        {
            "name": "Dummy name",
            "desc": "Lorem ipsum etc."
        }
    ],
    "category3": [
        {
            "name": "Blah",  
            "desc": "Blah blah"
        }
    ]
}

Html:

<div ng-repeat="category in vm.jsonData track by $index">
    <h3>{{ category }}</h3>
    <ul>
        <li ng-repeat="item in category">
            <span><b>{{ item.name }}</b></span><br/>
            <span>{{ item.desc }}</span>
        </li>
    </ul>
</div>

So far I can get name and desc properly but I miss category in html. Any help would be appreciated.

2 Answers 2

2

You need ng-repeat as <div ng-repeat="(key, value) in vm.jsonData track by $index">

DEMO

var app = angular.module('testApp',[]);
app.controller('testCtrl',function(){
  this.jsonData = {
    "category1": [
        {
            "name": "Some title",
            "desc": "And its description"
        },
        {
            "name": "Another title here",
            "desc": "Also description here"
        }
    ],
    "category2": [
        {
            "name": "Dummy name",
            "desc": "Lorem ipsum etc."
        }
    ],
    "category3": [
        {
            "name": "Blah",  
            "desc": "Blah blah"
        }
    ]
};

 vm = this;

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl as vm">
<div ng-repeat="(key, value) in vm.jsonData track by $index">       
    <ul>    
     {{key}} 
        <li ng-repeat="item in value">
            <span>{{ item.name }}</span>
            <span>{{ item.desc }}</span>
        </li>
    </ul>
</div>
</body>

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

3 Comments

What is the use of <h3>{{ category }}</h3>?? I have just removed in Edit
@RameshRajendran Thanks :) this is why Code reviews are important :P
@Sajeetharan thanks, the way with (key, value) in vm.jsonData helped to solve the problem.
1

You need to access key of the element which is "category1" in your case.

you can do this by using this syntax

ng-repeat="(key, value) in data"

here working jsfiffle for your example

2 Comments

Thanks. The way with (key, value) in vm.jsonData helped to solve the problem
@Dozent Welcome

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.