ng-repeat中的Angularjs条件元素

时间:2016-06-30 15:44:13

标签: html angularjs angularjs-ng-repeat

我在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语句循环来确定要使用的元素,但是在角度中你似乎必须为ng-repeat创建一个元素。在html中,您无法使用其他元素(<option><div>)包装每个<span>。所以我被卡住了。

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

2 个答案:

答案 0 :(得分:0)

希望这有帮助。

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>
这是你在找。

答案 1 :(得分:0)

看起来你想要做的事情是不可能的(如果我正确理解这一点)。看看Option Groups

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