7

由于某种原因,当我在资源 1 和资源 2 之间切换时,我的控制器被双重调用。

这是代码:

索引.html

<!DOCTYPE html>
<html ng-app="multiple_calls">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <a href="#res/1">1</a>
    <a href="#res/2">2</a>

    <div ng-view>
    </div>
  </body>

</html>

应用程序.js

var app = angular.module('multiple_calls', []);

app.
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/res/:id', {templateUrl: 'res.html',
                        controller: 'res'
      });
}]);


app.controller('MainCtrl', function($scope) {
});

app.controller('res', function($scope, $routeParams) {
  console.log('resource called')
  $scope.id = $routeParams.id;
});

res.html

{{id}}

http://plnkr.co/edit/HsCJmbllOcnlvlc1oiHa?p=preview

如果单击第 1 项,然后单击第 2 项,您会看到“调用的资源”打印了 3 次:资源之间的每次更改打印 2 次。

任何线索为什么会发生这种情况?

4

4 回答 4

14

发现了一个完全相同的问题:

AngularJs:使用 $routeProvider 调用控制器两次

解决方案是在路由器url末尾添加“/”:

-      when('/res/:id',
+      when('/res/:id/',
于 2013-10-04T09:39:31.737 回答
1

如果您更改为角度版本 1.1.5,这也适用

于 2013-10-04T09:40:47.300 回答
0

当我编写指令并包含控制器时,我仍在学习角度并且遇到了这个问题。

我希望能帮助别人,因为我花了很长时间来看看我做了什么:

.directive("list", function() {
  return {
    restrict: "E",
    transclude: true,
    replace: false,
    templateUrl: "contacts/list",
    controller: "CMSController", //- not needed at all
    controllerAs: 'cCtrl'//- not needed at all
  };
})

function config($routeProvider, $locationProvider, $httpProvider) {
  $routeProvider
   ....
    .when('/CMS', {
      templateUrl: 'contacts/index',
      controller: 'CMSController',
      controllerAs: 'cCtrl',
      access: {restricted: true}
    })
  ....
于 2016-07-02T06:03:17.520 回答
0

对我有用的另一种解决方案是,如果您定义了一个指令,请尽量不要将其控制器设置为多次调用的控制器,只需使用app.directive.

    app.directive('myDirective',[ '$window', function ($window) {
    function link(scope, element) {
           // stuff
        });
    };

    return {
      restrict: 'A',
      scope: {offset: "@"},
      link: link,
      // controller: myCtrl //myCtrl was called multiple I comment this line
    };
  }]);
于 2018-11-14T13:40:24.133 回答