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


当前回答

应用路由器指定导航到MyController,如下所示:

$routeProvider.when('/',
                   { templateUrl: 'pages/home.html',
                     controller: MyController });

但我在home。html中也有这个:

<div data-ng-controller="MyController">

这对控制器进行了两次消化。从HTML中删除data-ng-controller属性解决了这个问题。或者,controller:属性可以从路由指令中删除。

使用选项卡导航时也会出现此问题。例如,app.js可能包含:

  .state('tab.reports', {
    url: '/reports',
    views: {
      'tab-reports': {
        templateUrl: 'templates/tab-reports.html',
        controller: 'ReportsCtrl'
      }
    }
  })

相应的报告标签HTML可能类似于:

<ion-view view-title="Reports">
  <ion-content ng-controller="ReportsCtrl">

这也将导致运行控制器两次。

其他回答

只是想再添加一个控制器可以init两次的情况(这是实际的angular.js 1.3.1):

<div ng-if="loading">Loading...</div>
<div ng-if="!loading">
    <div ng-view></div>
</div>

在本例中为$route。ng-view初始化时,Current已经设置。会导致双重初始化。

要修复它,只需将ng-if更改为ng-show/ng-hide,一切都将正常工作。

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

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

由于不同的原因,我已经有了这个双重初始化。对于我的应用程序中的一些路由转换,我想强制滚动到接近页面顶部(例如在分页搜索结果中……)单击next会将您带到第2页的顶部)。

我通过在$viewContentLoaded上的$rootScope $中添加一个侦听器来实现这一点(基于某些条件)

$location.hash('top');

无意中,这导致我的路由被重新评估,控制器被重新初始化

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

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.

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

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

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

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