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


当前回答

在我的例子中,这是因为我使用的url模式

我的url是/ui/project/:parameter1/:parameter2。

我不需要在所有状态改变的情况下都使用paramerter2。在我不需要第二个参数的情况下,我的url将像/ui/project/:parameter1/。所以每当我有状态改变时,我都会刷新控制器两次。

解决方案是将parameter2设置为空字符串并进行状态更改。

其他回答

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

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

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

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

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

这个答案中的决议:

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

特此补充,以供参考:

在同样运行在页面上的指令中引用控制器也可能导致双控制器代码执行。

e.g.

return {

            restrict: 'A',
            controller: 'myController',
            link: function ($scope) { ....

当你也有ng-controller="myController"在你的HTML

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