Skip to content Skip to sidebar Skip to footer

How To Output Elements In A Json Array With Angularjs

JSON array defined in scope: $scope.faq = [ {'Question 1': 'Answer1'}, {'Question 2': 'Answer2'} ]; HTML:
{{f}}

Solution 1:

Change your json array in scope like;

$scope.faq = [
        {key: "Question 1",
         value: "Answer1"},

        {key: "Question 2",
         value: "Answer2"}
    ];

And in your view;

<divng-repeat="f in faq">
    {{f.key}}-{{f.value}}
</div>

Solution 2:

Due to it being within an array, you will have to loop through the key values of each object.

http://fiddle.jshell.net/TheSharpieOne/QuCCk/

<divng-repeat="value in faq"><divng-repeat="(question,answer) in value">
        {{question}} - {{answer}}
    </div></div>

Alternately: If you have just a simple object:

$scope.faq = {
     "Question 1": "Answer1",
     "Question 2": "Answer2"
};

You could avoid the second repeat

<divdata-ng-repeat="(question,answer) in faq">
        {{question}} - {{answer}}
</div>

http://fiddle.jshell.net/TheSharpieOne/D3sED/

Solution 3:

$scope.faq = [
    "Answer1",
    "Answer2"
];


<div ng-repeat="answer in faq">
    Question {{$index+1}}-{{answer}}
</div>

Solution 4:

If you are using ECMA5 compliant browsers, you could try,

<div ng-repeat="f in faq">
    {{Object.keys(f)[0]}}-{{f[Object.keys(f)[0]]}}
</div>

Of course, this will only work reliably if your object only has 1 key. If it has more than one key, your best bet will be to write a filter function that gets the key names, which you can then use to extract the relevant keys.

Solution 5:

Check my code: http://plnkr.co/edit/NGEcK7iieFRtvt7WP48A?p=preview

ng-repeat needs an array, for each object in the array, you need keys bound with values.

Post a Comment for "How To Output Elements In A Json Array With Angularjs"