我知道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中。我显然还在学习,因为我已经用我的头撞它很多年了!


当前回答

我刚刚解决了我的问题,其实很令人失望。这是一个离子混合应用程序,我使用ui-router v0.2.13。在我的例子中,有一个epub阅读器(使用epub.js),一旦我导航到我的图书馆并选择任何其他书籍,它就会连续报告“没有找到文档”。当我重新加载浏览器的书被完美地渲染,但当我选择另一本书得到同样的问题再次。

我的解决方法很简单。我刚刚从$state.go("app. go ")中删除了reload:true。reader", {fileName: fn, reload: true});在我的图书馆控制器

其他回答

在我的例子中,我发现使用相同控制器的两个视图。

$stateProvider.state('app', {
  url: '',
  views: {
    "viewOne@app": {
      controller: 'CtrlOne as CtrlOne',
      templateUrl: 'main/one.tpl.html'
    },
    "viewTwo@app": {
      controller: 'CtrlOne as CtrlOne',
      templateUrl: 'main/two.tpl.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.

我有同样的问题,在尝试了所有的答案后,我终于发现我在我的视图中有一个指令,绑定到相同的控制器。

APP.directive('MyDirective', function() {
  return {
    restrict: 'AE',
    scope: {},
    templateUrl: '../views/quiz.html',
    controller: 'ShowClassController'
}
});

删除指令后,控制器停止被调用两次。现在我的问题是,如何使用这个绑定到控制器作用域的指令而不出现这个问题?

在这个问题上,我把我的应用程序和它所有的依赖项都撕成了碎片(详细信息在这里:AngularJS应用程序初始化两次(尝试了通常的解决方案..))

最后,这都是巴塔朗Chrome插件的错。

这个答案中的决议:

我强烈建议大家在修改代码之前先禁用每一篇文章。

我有同样的问题,在一个简单的应用程序(没有路由和一个简单的ng-controller引用),我的控制器的构造函数运行了两次。最后,我发现我的问题是以下声明自动引导我的AngularJS应用程序在我的Razor视图

<html ng-app="mTest1">

我还使用angular手动引导它。引导。

angular.bootstrap(document, [this.app.name]);

所以去掉其中一个,对我有用。