AngularJS控制器执行两次(不是因为路由器)

AngularJS controller executes twice (not because of router)

本文关键字:两次 是因为 路由器 控制器 执行 AngularJS      更新时间:2023-09-26

据我所知,此问题的最常见原因是当控制器包含在模板和路由提供程序中时。就我而言,只有包含此html的父模板包含在路由器中,并且具有自己的控制器。子模板作为菜单选择的结果被包括在内

因此,每当选择菜单项时,都会加载模板,并且控制器中的所有内容都会执行两次。它可以是ng开关或ng包含的产品吗?

<span ng-switch on="selection">
    <div ng-switch-when="0">
        <div ng-include="'partials/one.html'" ng-controller="oneController"></div>
    </div>
    <div ng-switch-when="1">
        <div ng-include="'partials/two.html'" ng-controller="twoController"></div>
    </div>
    <div ng-switch-when="2">
        <div ng-include="'partials/three.html'" ng-controller="threeController"></div>
    </div>
</span>

编辑:

包含

的部分不再包含控制器。我已经三重检查了这些控制器是否没有提到这段代码以外的任何地方。一个/两个/三个部分的内容如下所示,控制器仍然运行两次。

<div>Nothing to see here.</div>

我在这里做一个有根据的猜测......但是你的"'partials/one.html'"也有ng-controller="oneController"吗? 如果是这样,则需要从包含div 或部分中删除 ng-controller 声明。