7

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"}

What I want output to look like:

Question 1 - Answer1
Question 2 - Answer2

How it seems like it should work:

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

... but it doesn't.

Robert Christian
  • 18,218
  • 20
  • 74
  • 89

5 Answers5

12

Change your json array in scope like;

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

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

And in your view;

<div ng-repeat="f in faq">
    {{f.key}}-{{f.value}}
</div>
BKM
  • 6,949
  • 7
  • 30
  • 45
  • Perfect, this works. I like the alternative:
    {{question}} - {{answer}}
    , which doesn't require adding key/value, but I think this is more extensible and closer to answering the question.
    – Robert Christian Aug 26 '13 at 14:59
8

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/

<div ng-repeat="value in faq">
    <div ng-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

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

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

cubap
  • 37
  • 8
TheSharpieOne
  • 25,646
  • 9
  • 66
  • 78
0
$scope.faq = [
    "Answer1",
    "Answer2"
];


<div ng-repeat="answer in faq">
    Question {{$index+1}}-{{answer}}
</div>
Fly_pig
  • 155
  • 8
0

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.

gos1
  • 360
  • 5
  • 10
  • While working I find it far from being concise and readable. As you have also noticed yourself - adding unrelated keys to your object would break this ngRepeat, which means it's not a good design. – Majki Feb 02 '14 at 22:50
0

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.

Z.T. Yang
  • 342
  • 1
  • 5