4

是否可以在ng-repeat内部嵌套ng-switch-when

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

运行时出现以下异常:

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

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

谢谢!

编辑

我想要完成的是以下

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

所以我想知道我是否可以使用ng-repeat来帮助减少上面多余的 HTML 模板代码(ng-switch-when)。

4

2 回答 2

3

不,你不能嵌套它们。ng-switch 在 ng-controller $scope 上的 $$watchers 数组中添加一个条目。ng-repeat 为每次迭代创建一个新的子作用域。当遇到 ng-switch-when 时,(我在这里猜测)它在当前 $scope (现在是 ng-repeat 子范围)中找不到任何 ng-switch 信息,所以它失败了。

更新:我对此进行了更多研究。错误发生在 1.0.3,但不是 1.0.4(但它也不适用于 1.0.4)。实际发生的是 ng-switch-when 范围是控制器范围的子范围,而不是 ng-repeat 迭代子范围。因此,routeng-switch-when 指令不可见。这是一个使用 1.0.4 的小提琴——您可以单击一些链接来查看控制器、ng-repeat 和 ng-switch-default 范围。检查 ng-switch-default 范围,您可以看到它的 $parent 是控制器的范围,而不是 ng-repeat 范围。

于 2013-02-08T15:57:59.633 回答
1

我认为 ng-switch on 应该跟在 ng-switch-when 之后。在你的情况下,你有一个

<div ng-repeat="route in routes">介于两者之间。

您显示的逻辑不需要 ng-switch 或者我可能遗漏了一些东西。

于 2013-02-08T07:27:42.193 回答