据我所知,此问题的最常见原因是 Controller 包含在模板和路由提供程序中。就我而言,只有包含此 html 的父模板包含在路由器中,并且有自己的 Controller 。由于菜单选择而包含子模板
因此,每当选择菜单项时,模板就会被加载,并且 Controller 中的所有内容都会执行两次。它可以是 ng-switch 或 ng-include 的产品吗?
<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>
编辑:
包含的部分不再包含 Controller 。我已经三重检查,除了这段代码之外,没有在任何地方提到这些 Controller 。一/二/三部分的内容如下所示, Controller 仍然运行两次。
<div>Nothing to see here.</div>
最佳答案
我在这里做了一个有根据的猜测...但是你的 "'partials/one.html'"
中也有一个 ng-controller="oneController"
它?如果是这样,您需要从包含 div 或部分内容中删除 ng-controller 声明。
关于javascript - AngularJS Controller 执行两次(不是因为路由器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770371/