Reputation: 950
I have an object, which has objects inside, and arrays in child objects. Here's the structure:
var keywords = {
"Animals" : {
"Pets" : [
"Guppy", "Parrot", "Goldfish", "Dog", "Cat"
],
"Wild animals" : [
"Tiger", "Ant", "Tetra", "Peafowl", "Mongoose"
],
"Domestic animals" : [
"Cow", "Pig", "Goat", "Horse"
]
},
"Food" : {
"Fast food" : [
"Cheeseburger", "Hamburger"
],
"Dessert" : [
"Chocolate", "Cookie", "Cake", "Pie"
]
},
"Vehicle" : {
"Motorcycle" : [
"Harley Davidson"
],
"Car" : [
"Lamborghini", "Ferrari", "Bugatti", "BMW", "Mercedes"
]
},
"Movie" : {
"Science fiction" : [
"Sunshine", "Interstellar", "The Moon", "Oblivion", "Star Trek", "Star Wars"
]
}
};
I've made a foreach loop for looping through the elements inside and print them on screen:
angular.forEach(keywords, function(value, key) {
console.log(key);
angular.forEach(value, function(value, key) {
console.log(key);
angular.forEach(value, function(value, key) {
console.log(value);
})
})
})
Now, I'm trying to do the same with ng-repeat directive on a div (that has a div in it, and another in the child div), but can't make it work, have no clue how to start it. Any idea?
Upvotes: 1
Views: 3278
Reputation: 381
I think we are not using ng-repeat with this type of array.
You should go throw with this logic.
$scope.html ="";
angular.forEach(keywords, function(value, key) {
$scope.html += "<div>"+ key ;
angular.forEach(value, function(value, key) {
$scope.html += "<div>"+ key ;
angular.forEach(value, function(value, key) {
$scope.html += "<div>"+ key + "</div>";
})
$scope.html += "</div>";
})
$scope.html += "</div>";
})
and Print 'html' scope into your HTML page.
{{html}}
I know this is not perfect solution but it's trick to fix you current problem.
Upvotes: 0
Reputation: 13953
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.keywords = {
"Animals": {
"Pets": [
"Guppy", "Parrot", "Goldfish", "Dog", "Cat"
],
"Wild animals": [
"Tiger", "Ant", "Tetra", "Peafowl", "Mongoose"
],
"Domestic animals": [
"Cow", "Pig", "Goat", "Horse"
]
},
"Food": {
"Fast food": [
"Cheeseburger", "Hamburger"
],
"Dessert": [
"Chocolate", "Cookie", "Cake", "Pie"
]
},
"Vehicle": {
"Motorcycle": [
"Harley Davidson"
],
"Car": [
"Lamborghini", "Ferrari", "Bugatti", "BMW", "Mercedes"
]
},
"Movie": {
"Science fiction": [
"Sunshine", "Interstellar", "The Moon", "Oblivion", "Star Trek", "Star Wars"
]
}
};
});
.section1{
background-color: CornflowerBlue;
}
.section2{
background-color: lightblue;
}
.section3{
background-color: Azure ;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="(keyword, list) in keywords" class="section1">
{{keyword}}
<div ng-repeat="(name, items) in list" class="section2">
{{name}}
<div ng-repeat="item in items" class="section3">
{{item}}
</div>
</div>
</div>
</body>
Upvotes: 2