0

I have an an array of objects in 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"}]}
]

Using angularJS 1.2 (I need to support IE8) i would like to create:

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

So I need to loop over the top level items creating an option for each but for those with sub items I need to create an option group then loop over the subitems creating an option for each.

In any other language I would do a loop with an if statement to determine what element to use, however in angular you seem to have to create an element for a ng-repeat. In html you can't wrap each <option> with another element (<div> or <span>). So I'm stuck.

I need an element-less ng-repeat. Can anyone suggest any solution?

Robin Fuller
  • 153
  • 2
  • 9
  • I'm not understanding this completely. I created a Plunker of your code. Can you use it to explain what it is you want it to do? http://plnkr.co/edit/uyQBNabfVMQCXgKVpQmi?p=preview – Rani Radcliff Jun 30 '16 at 16:05

2 Answers2

0

Hope this help.

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>
Is this you are looking for.
Saurabh Sarathe
  • 231
  • 2
  • 11
0

It looks like what you are trying to do is not possible (If I am understanding this correctly). Take a look here Option Groups

1: https://www.w3.org/TR/html401/interact/forms.html#h-17.6 and here: StackOverflow

Community
  • 1
  • 1
Rani Radcliff
  • 4,856
  • 5
  • 33
  • 60