我知道AngularJS会将一些代码运行两次,有时甚至更多,比如$watch events,不断检查模型状态等等。

然而我的代码:

function MyController($scope, User, local) {

var $scope.User = local.get(); // Get locally save user data

User.get({ id: $scope.User._id.$oid }, function(user) {
  $scope.User = new User(user);
  local.save($scope.User);
});

//...

执行两次,将2条记录插入到我的DB中。我显然还在学习,因为我已经用我的头撞它很多年了!


当前回答

如果你知道你的控制器无意中执行了不止一次,试着在你的文件中搜索有问题的控制器的名称,例如:search: MyController在所有文件中。很可能它被复制粘贴到其他html/js文件中,当你开发或使用这些部分/控制器时忘记更改它。来源:我犯了这个错误

其他回答

如果你知道你的控制器无意中执行了不止一次,试着在你的文件中搜索有问题的控制器的名称,例如:search: MyController在所有文件中。很可能它被复制粘贴到其他html/js文件中,当你开发或使用这些部分/控制器时忘记更改它。来源:我犯了这个错误

AngularJS docs - ngController 注意,还可以通过声明DOM将控制器附加到DOM 在路由定义中通过$route服务。一个常见的错误是 在模板中使用ng-controller再次声明控制器 本身。这将导致控制器被附加并执行 两次。

当你在ng-view指令中使用ngRoute时,控制器默认会附加到那个dom元素(如果你使用ui-router,则会附加到ui-view)。因此,您不需要在模板中再次附加它。

在某些情况下,当你没有像这样纠正close you指令时,你的指令会运行两次:

< my-directive >一些内容< my-directive >

这将运行你的指令两次。 还有另一种情况,当你的指令运行两次:

确保你没有在index.html中包含你的指令两次!

我刚刚讲过这个问题,但这个问题与公认的答案不同。我真的要把这些留给未来的自己,包括我为解决这个问题所采取的步骤。

Remove redundant controller declarations Check trailing slashes in routes Check for ng-ifs Check for any unnecessary wrapping ng-view calls (I accidentally had left in an ng-view that was wrapping my actual ng-view. This resulted in three calls to my controllers.) If you are on Rails, you should remove the turbolinks gem from your application.js file. I wasted a whole day to discover that. Found answer here. Initializing the app twice with ng-app and with bootstrap. Combating AngularJS executing controller twice When using $compile on whole element in 'link'-function of directive that also has its own controller defined and uses callbacks of this controller in template via ng-click etc. Found answer here.

我的问题真的很难找到。最后,当网页缺少图像时,问题就出现了。src缺少一个Url。这发生在MVC 5 Web控制器上。为了解决这个问题,当没有真实图像可用时,我添加了透明图像。

<img alt="" class="logo" src="">