2

I have an array in Angular like this:

$scope.test = [
  {'item1' : 'answer1' },
  {'item2' : 'answer2' },
  {'item3' : 'answer3' }
];

And so on...

Now there's 2 things I want to do. Firstly I want to use an ng-repeat to iterate through the array and display the keys and values separately. I tried this:

<div ng-repeat="(key,value) in test">
  {{key}} = {{value}}
</div>

But that produces results like this:

0  = {"item1" : "answer1"}
1  = {"item2" : "answer2"}
2  = {"item3" : "answer3"}

Whereas I want it to display like this:

item1  = answer1
item2  = answer2
item3  = answer3

The second thing I'd like to do is use the keys to display results from a different array. For example I have this array:

$scope.item1.question = 'some question';

So as I'm going through the ng-repeat I'd like to do something like this:

{{key}}.question

to display the string 'some question'.

But this doesn't do anything...

1 Answer 1

3

1. Use nested ng-repeats.

The ng-repeat is only looping over the array and so its writing out the element's index as the key. You need to nest another ng-repeat to iterate over the contained objects:

<div ng-repeat="obj in test">
    <div ng-repeat="(key,value) in obj">
        {{key}} = {{value}}
    </div>
</div>

2. Use square brackets notation and an object wrapper.

To access an object using dynamic key that comes from another object inside ng-repeat, use array notation that allows expressions:

$scope.model = {
    item1: {
        question : 'some question 1'
    },
    item2: {
        question : 'some question 2'
    },
    item3: {
        question : 'some question 3'
    }
}; 

HTML:

<div>
    {{ model[key].question }}
</div>

Fiddle

1
  • Ah nested ng-repeats! I didn't know you could do that. Thanks, but is there a way now to use the key to call the extra array? like {{key}}.question but where the {{key}} is treated as a string so it's the same as calling item.question for example. Commented Aug 1, 2014 at 11:05

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.