2

In a webapp I'm developing, I'm trying to nest a ng-switch within a ng-switch (within an ng-repeat) and finding that the inner switch evaluation is not happening.

In the cut-down example below (and on Plunker), I would expect to see:

  • A
  • B
  • D
  • G
  • H

But what I actually see is:

  • A
  • B
  • (nothing)
  • (nothing)
  • H

On inspection with Firebug, the 3rd and 4th fields have no children beyond the <div ng-switch on="el.n1.hasOwnProperty('n2')"> div.

My apologies for the use of hasOwnProperty, but I'm dealing with some JSON with optional fields. If there's a better way to switch on the existence of a field, I'd be all ears.

<!doctype html>
<html lang="en" ng-app>
<head>
        <meta charset="UTF-8"/>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
        <script>
            function TestController($scope)
            {
                $scope.testExample = [
                    { n : "A" },
                    { n : "B" },
                    {
                        n : "C",
                        n1 : { x : "D" }
                    },
                    {
                        n : "E",
                        n1 :
                        {
                            x : "F",
                            n2 : { y : "G" }
                        }
                    },
                    { n : "H" }
                ];
            }
        </script>
</head>

<body ng-controller="TestController">

    <ul ng-repeat="el in testExample">
        <li ng-switch on="el.hasOwnProperty('n1')">
            <div ng-switch-when="true"> 

                <div ng-switch on="el.n1.hasOwnProperty('n2')">
                    <div ng-switch-when="true">
                        {{el.n1.n2.y}}
                    </div>

                    <div ng-switch-default>
                        {{el.n1.x}}
                    </div>
                </div>

            </div>

            <div ng-switch-default> 
                {{el.n}}
            </div>
        </li>
    </ul>
</body>
</html>

Any help gratefully received.

1 Answer 1

3

You can try to use Object.keys(el).indexOf('n1') > 0 instead of hasOwnProperty

<ul ng-repeat="el in testExample">
    <li ng-switch on="Object.keys(el).indexOf('n1') > 0">
        <div ng-switch-when="true">
            <div ng-switch on="Object.keys(el.n1).indexOf('n2') > 0">
                <div ng-switch-when="true">{{el.n1.n2.y}}</div>
                <div ng-switch-default>{{el.n1.x}}</div>
            </div>
        </div>
        <div ng-switch-default>{{el.n}}</div>
    </li>
</ul>

In the controller, don't forget this line

$scope.Object = Object;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.