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


当前回答

特此补充,以供参考:

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

e.g.

return {

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

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

其他回答

特此补充,以供参考:

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

e.g.

return {

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

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

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

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

or

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

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

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

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.

在这里加上我的案例:

我使用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 docs - ngController 注意,还可以通过声明DOM将控制器附加到DOM 在路由定义中通过$route服务。一个常见的错误是 在模板中使用ng-controller再次声明控制器 本身。这将导致控制器被附加并执行 两次。

当你在ng-view指令中使用ngRoute时,控制器默认会附加到那个dom元素(如果你使用ui-router,则会附加到ui-view)。因此,您不需要在模板中再次附加它。