Reputation: 203
In my Angular app, I am using ng-repeat
to cycle through all the items in a JSON object I have. So for example, for my JSON object:
$scope.animals =
{
horse: {
sound: "Nay",
legs: 4,
}
beaver: {
sound: "thwack",
legs: 2
}
}
I want to cycle through to get a list consisting of Horse, Beaver
i.e.
<div ng-repeat="(key, value) in animals">
<div class="niceBox">
<h1> {{key}} </h1>
</div>
</div>
but for each animal, I want to have a button that takes the whole object and adds it to a list of my favorite animals. Something like this:
<div ng-repeat="(key, value) in animals">
<div class="niceBox">
<h1> {{key}} </h1>
<div ng-click="addToFavorites(animal)">Add To Favorites</div>
</div>
</div>
The Trouble Is that I can't just pass animal
as a parameter since I broke up the ng-repeat
into (key, value)
already.
How do I reassemble (key, value)
so I could use the object as a whole?
Upvotes: 0
Views: 35
Reputation: 7214
Your question is misleading, because there's no original "object" you want to re-assemble - there's just property names and values. If you had a single object for the animal in the first place:
var animals = [{
name: 'horse',
sound: ...,
...
}, {
name: 'beaver',
...
}, ...];
there would be nothing to "re-assemble", you'd just use it:
<div ng-repeat="animal in animals">
{{animal.name}}
<button ng-click="addToFavorites(animal)">...</button>
</div>
Upvotes: 3
Reputation: 1052
Try by this this
<div ng-repeat="(key, value) in animals">
<div class="niceBox">
<h1> {{key}} </h1>
<div ng-click="addToFavorites(key, value)">Add To Favorites</div>
</div>
</div>
And in your controller
$scope.addToFavorites = function(key, value) {
$scope.animal = {};
animal[key] = value;
/** your code **/
}
Upvotes: 1