Or Weinberger
Or Weinberger

Reputation: 7472

AngularJS loop through JSON and check if multidimensional

I have the following controller:

controller('homepageCtrl', function ($scope) {
    $scope.menu = {
      "Home": "/",
      "Data Sources": {
        "Add": "/datasources/add",
        "Edit": "/datasources/edit",
        "List": "/datasources/list"
      },
      "Test": "/test"
    }
});

And the following HTML (JADE)

div(ng-controller='homepageCtrl')
        div(ng-repeat='(key, val) in menu')
          {{key}} - {{val}}
          div(ng-repeat='(k, v) in val')
            {{k}} - {{v}}

I want to loop through the JSON object but also to check if the current value is another JSON object and if it is then to iterate through it as well.

The code above currently generates:

Data Sources - {"Add":"/datasources/add","Edit":"/datasources/edit","List":"/datasources/list"}
Add - /datasources/add
Edit - /datasources/edit
List - /datasources/list
Home - /
0 - /
Test - /test

However I want to it generate:

Add - /datasources/add
Edit - /datasources/edit
List - /datasources/list
Home - /
0 - /
Test - /test

Upvotes: 0

Views: 3057

Answers (1)

Moritz Petersen
Moritz Petersen

Reputation: 13057

Why not just using ng-if:

<div ng-repeat="(key, val) in menu">
    <div ng-repeat="(k, v) in val" ng-if="typeof val == 'object'">
        ...
    </div>
</div>

Upvotes: 2

Related Questions