How to output elements in a JSON array using AngularJS

JSON array defined in scope:

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

HTML:

 <div ng-repeat="f in faq"> {{f}} </div> 

Output:

 {"Question 1": "Answer1"} {"Question 2": "Answer2"} 

I want the output to look like this:

 Question 1 - Answer1 Question 2 - Answer2 

It seems like it should work:

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

... but it is not.

+7
json javascript html angularjs output
source share
5 answers

Change your json array in scope:

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

And, in your opinion,

 <div ng-repeat="f in faq"> {{f.key}}-{{f.value}} </div> 
+12
source share

Due to the fact that it is inside the array, you will need to skip the key values ​​for each object.

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

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

As an alternative:
If you have a simple object:

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

You can avoid the second repetition

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

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

+8
source share
 $scope.faq = [ "Answer1", "Answer2" ]; <div ng-repeat="answer in faq"> Question {{$index+1}}-{{answer}} </div> 
0
source share

If you use ECMA5 compatible browsers, you can 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 has only 1 key. If you have several keys, the best option would be to write a filter function that gets the key names, which you can then use to extract the corresponding keys.

0
source share

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

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

0
source share

All Articles