badallen
badallen

Reputation: 1127

Angular Error when enbedding ng-switch inside of ng-repeat

Is it possible to nest ng-switch-when insides of ng-repeat?

<div ng-controller="UserController">
                            <div ng-switch on="renderPath">
                                <div ng-repeat="route in routes">
                                    <div ng-switch-when="route.path">
                                        <div ng-include src="route.url"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

I got the following exception when I run it:

    Error: Argument '?' is required
pa@http://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:16 ...

<!-- ngSwitchWhen: route.path -->

Thank you!

EDIT

What I am trying to accomplish is the following

<div ng-switch on="renderPath">
                                    <div ng-switch-when="path1">
                                        <div ng-include src="url1"></div>
                                    </div>
                                    <div ng-switch-when="path2">
                                        <div ng-include src="url2"></div>
                                    </div>
                                    <div ng-switch-when="path3">
                                        <div ng-include src="url3"></div>
                                    </div>
                                </div>
                            </div>

So I was wondering if I can use ng-repeat to help ne reduce the redundant HTML template code (ng-switch-when) above.

Upvotes: 4

Views: 3736

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364707

No you can't nest them. ng-switch adds an entry to the $$watchers array on the ng-controller $scope. ng-repeat creates a new child scope for each iteration. When ng-switch-when is encountered, (I'm guessing here) it can't find any ng-switch information in the current $scope (which is now the ng-repeat child scope), so it fails.

Update: I looked into this some more. The error happens with 1.0.3, but not 1.0.4 (but it doesn't work with 1.0.4 either). What is actually going on is that the ng-switch-when scope is a child scope of the controller's scope, not the ng-repeat iteration child scope. Therefore, route is not visible to the ng-switch-when directives. Here's a fiddle that uses 1.0.4 -- you can click some links to see the controller, ng-repeat, and ng-switch-default scopes. Examining the ng-switch-default scope, you can see that its $parent is the controller's scope, not an ng-repeat scope.

Upvotes: 3

Chandermani
Chandermani

Reputation: 42669

I think ng-switch on should be followed by ng-switch-when. In your case you are having a

<div ng-repeat="route in routes">in between.

The logic you have shown does not require ng-switch or maybe i am missing something.

Upvotes: 1

Related Questions