【问题标题】:For Each Loops in Angular JS对于 Angular JS 中的每个循环
【发布时间】:2016-10-16 22:21:16
【问题描述】:

我刚开始学习 AngularJS,我需要能够创建带有标题的列表,然后是其中的项目。

第 1 类
项目 1
项目 2


第 2 类
项目 1
项目 2
等等

如何创建一个循环来获取类别标题,然后还获取该类别中的项目?

在代码中我想这样显示:

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

很抱歉,我无法提供更多信息,我对语言的了解不足,无法提供更多信息。提前致谢!

编辑: 我试过了:

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

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

有了这个,我不知道如何为这些项目再深入一层。

我也在尝试做这样的事情(我不知道它是否会起作用):

var categories = {$category: $items}

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

【问题讨论】:

  • @Soviut 编辑了一些我尝试过的东西,不幸的是仍然没有太大帮助

标签: javascript angularjs loops foreach


【解决方案1】:

假设你有这样的数据结构;一个类别数组,每个类别包含一个name 属性和一个包含属于该类别的所有项目的items 数组。

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

您可以在模板中使用ng-repeat 循环来表示这一点,方法是遍历categories 数组并在每个循环内,对该类别中的items 数组执行嵌套循环:

<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>

【讨论】:

    【解决方案2】:

    使用 ng-repeat。这是一个例子:

    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>
    

    确保 section 是该 HTML 所在控制器的 $scope 中的变量。

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2014-05-04
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-22
      相关资源
      最近更新 更多