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...
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...
Share Improve this question edited Aug 1, 2014 at 11:18 AlwaysALearner 44k9 gold badges97 silver badges78 bronze badges asked Aug 1, 2014 at 10:49 CaribouCodeCaribouCode 14.4k33 gold badges111 silver badges186 bronze badges1 Answer
Reset to default 31. Use nested ng-repeat
s.
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 es 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744209230a4563254.html
评论列表(0条)