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


当前回答

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

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

or

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

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

其他回答

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

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

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

当在Angular 1.3+中使用Angular -ui-router时,有一个关于在路由转换时渲染视图两次的问题。这也导致执行了两次控制器。提出的解决方案没有一个对我有效。

但是,将angular-ui-router从0.2.11更新到0.2.13,为我解决了这个问题。

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

在这里加上我的案例:

我使用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”。一旦我像上面那样显式地对参数进行编码,问题就解决了。

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