Kiss Koppány Kiss Koppány - 1 month ago 8
AngularJS Question

AngularJS ng-repeat for object contains objects and arrays

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?

Answer

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>