【问题标题】:Angularjs conditional elements in ng-repeatng-repeat中的Angularjs条件元素
【发布时间】:2016-07-01 01:34:23
【问题描述】:

我在 javascript 中有一个对象数组:

[
    {id: 1, name: "Item 1", subItems: []},
    {id: 2, name: "Item 2", subItems: []},
    {id: 3, name: "Item 3", subItems: [[
        {id: 4, name: "Item 3.1"},
        {id: 5, name: "Item 3.2"},
        {id: 6, name: "Item 3.3"}]}
]

使用 angularJS 1.2(我需要支持 IE8)我想创建:

<select>
    <option value="1">Item 1</option>
    <option value="1">Item 1</option>
    <optgroup label="Item 3">
        <option value="4">Item 3.1</option>
        <option value="5">Item 3.2</option>
        <option value="6">Item 3.3</option>
    </optgroup>
</select>

所以我需要遍历顶层项目,为每个项目创建一个选项,但对于那些有子项目的项目,我需要创建一个选项组,然后遍历子项目,为每个项目创建一个选项。

在任何其他语言中,我都会使用 if 语句进行循环以确定要使用的元素,但是在 Angular 中,您似乎必须为 ng-repeat 创建一个元素。在 html 中,您不能用另一个元素(&lt;div&gt;&lt;span&gt;)包装每个 &lt;option&gt;。所以我被困住了。

我需要一个无元素的 ng-repeat。任何人都可以提出任何解决方案吗?

【问题讨论】:

标签: html angularjs angularjs-ng-repeat


【解决方案1】:

希望对您有所帮助。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
 $scope.item = [
    {id: 1, name: "Item 1", subItems: []},
    {id: 2, name: "Item 2", subItems: []},
    {id: 3, name: "Item 3", subItems: [[
        {id: 4, name: "Item 3.1"},
        {id: 5, name: "Item 3.2"},
        {id: 6, name: "Item 3.3"}]
            ]}
            ]
});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <ul>
      <li ng-repeat="item in item">{{item.name}}
              <span ng-if="item.subItems" ng-repeat="subItems in item.subItems">
                 <ul>
                    <li ng-repeat="subItems in subItems">{{subItems.name}}</li>
                  </ul>
              </span>
      </li>
    </ul>
  </body>

</html>
这是你要找的。

【讨论】:

    【解决方案2】:

    看起来您尝试做的事情是不可能的(如果我理解正确的话)。看这里Option Groups

    1https://www.w3.org/TR/html401/interact/forms.html#h-17.6 和这里:StackOverflow

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 2013-03-03
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      相关资源
      最近更新 更多