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


当前回答

我在angular-route@1.6.7也有同样的问题,这是因为在regex路由的结尾额外的斜杠:

.when('/goods/publish/:classId/', option)

to

.when('/goods/publish/:classId', option)

而且工作正常。

其他回答

我一直在用AngularJS 1.4 rc构建这个问题,然后意识到上面的答案都不适用,因为在撰写本文时,它起源于Angular 1.4和Angular 2的新路由器库。因此,我要在这里提醒那些可能正在使用新的Angular路由库的人。

基本上,如果一个html页面包含一个ng-viewport指令来加载你的应用程序的部分,通过点击ng-link中指定的超链接将导致相关组件的目标控制器被加载两次。细微的区别在于,如果浏览器已经加载了目标控制器,那么重新单击相同的超链接只会调用该控制器一次。

还没有找到可行的解决方案,尽管我相信这个行为与shaunxu提出的观察是一致的,希望这个问题能在未来的新路由库构建中以及AngularJS 1.4版本中得到解决。

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

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.

我发现我的被调用两次是因为我从我的html调用了两次方法。

`<form class="form-horizontal" name="x" ng-submit="findX() novalidate >
 <input type="text"....>
 <input type="text"....>
 <input type="text"....>
 <button type="submit" class="btn btn-sm btn-primary" ng-click="findX()"
</form>`

突出显示的部分导致两次调用findX()。希望它能帮助到别人。

The problem I am encountering might be tangential, but since googling brought me to this question, this might be appropriate. The problem rears its ugly head for me when using UI Router, but only when I attempt to refresh the page with the browser refresh button. The app uses UI Router with a parent abstract state, and then child states off the parent. On the app run() function, there is a $state.go('...child-state...') command. The parent state uses a resolve, and at first I thought perhaps a child controller is executing twice.

在URL附加散列之前一切正常。 www.someoldwebaddress.org

一旦url被uirouter修改了, www.someoldwebaddress.org / childstate

...然后当我用浏览器刷新按钮刷新页面时,$stateChangeStart会触发两次,每次都指向childstate。

父状态的解析是触发两次的东西。

也许这只是一种拼凑;无论如何,这似乎为我消除了问题:在第一次调用$stateProvider的代码区域,首先检查window.location.hash是否为空字符串。如果是,一切都好;如果不是,则将window.location.hash设置为空字符串。那么,$state似乎只会尝试去某个地方一次,而不是两次。

此外,如果你不想依赖于应用程序的默认run和state.go(…),你可以尝试捕获散列值,并使用散列值来确定页面刷新前你所处的子状态,并在代码中设置state.go(…)的区域添加一个条件。

应用路由器指定导航到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">

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