0

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
Etc

Category 2
Item 1
Item 2
Etc

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>
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
</ul>

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

Edit: I have tried:

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

<div ng-repeat="category in categories">
    {{category}}
</div>

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
}
1
  • @Soviut Editied with some things I've tried, unfortunately not too helpful still Commented Oct 16, 2016 at 22:29

2 Answers 2

2

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>
  </ul>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Use ng-repeat. Here is an example:

Javascript:

var sections = {[
    {
        header: "Header1",
        content: ["one", "two", "three"]
    },
    {
        header: "Header2",
        content: ["one", "two", "three"]
    }
]};

HTML:

<div ng-repeat="section in sections">
    <h2>{{section.header}}</h2>   
    <ul>
        <li ng-repeat="item in section.content">
            "Item: " {{item}}
        </li>
    </ul>
</div>

Make sure sections is a variable in the $scope of the controller this HTML is part of.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.