Edward144 Edward144 - 4 days ago 4x
Javascript Question

For Each Loops in Angular JS

I'm just starting to learn AngularJS and I need to be able to create lists with a title and then items within it.

Category 1

Item 1

Item 2


Category 2

Item 1

Item 2


How can I create a loop to get the category title, and then also get the items within that category?

In the code I would like to display it like this:

<h2>Category 1</h2>
<li>Item 1</li>
<li>Item 2</li>

I'm sorry I can't give more information, I don't know enough about the language to provide more. Thanks in advance!

I have tried:

$scope.categories = ['category 1', 'category 2']

<div ng-repeat="category in categories">

With this I dont know how to go another layer deep for the items.

Also I'm trying to do something like this (I don't know if it will work):

var categories = {$category: $items}

angular.forEach(categories, function(category, items)) {
//Do Something


Assuming you had a data structure like this; An array of categories, each category containing a name attribute and an items array containing all items belonging to that category.

$scope.categories = [
        name: "Category1",
        items: [
            {name: "Item1"},
            {name: "Item2"},
            {name: "Item3"}
            // ...more items
    // ...more categories

You could represent this in your template using ng-repeat loops by looping over the categories array and inside each loop, perform a nested a loop over the items array in that category:

<div class="category" ng-repeat="category in categories">
  <h2>{{ category.name }}</h2>
  <ul class="items" ng-repeat="item in category.items">
    <li>{{ item.name }}</li>