我知道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-ui-router和$state。Go ('new_state', {foo: "foo@bar"})

一旦我将encodeURIComponent添加到参数中,问题就解决了:$state。go('new_state', {foo: encodeURIComponent("foo@bar")})。

发生了什么事? 参数值中的“@”字符不允许出现在url中。因此,angular-ui-router创建了我的控制器两次:在第一次创建时,它传递了原始的“foo@bar”,在第二次创建时,它将传递编码版本“foo%40bar”。一旦我像上面那样显式地对参数进行编码,问题就解决了。

其他回答

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

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

这个答案中的决议:

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

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(…)的区域添加一个条件。

我发现我的被调用两次是因为我从我的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()。希望它能帮助到别人。

对于那些使用ControllerAs语法的人,只需在$routeprovider中声明控制器标签,如下所示:

$routeprovider
        .when('/link', {
            templateUrl: 'templateUrl',
            controller: 'UploadsController as ctrl'
        })

or

$routeprovider
        .when('/link', {
            templateUrl: 'templateUrl',
            controller: 'UploadsController'
            controllerAs: 'ctrl'
        })

在声明了$routeprovider之后,不要像视图中那样提供控制器。相反,在视图中使用标签。

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

$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'
    }
  }
});