Angularjs: Controller is called multiple times

后端 未结 4 1321
我寻月下人不归
我寻月下人不归 2021-01-12 13:59

For some reason, my controller is double called, when I switch between resource 1 and resource2.

Here\'s the code:

index.html



        
相关标签:
4条回答
  • 2021-01-12 14:16

    one another solution which worked for me is that if you defined a directive, try not set its controller to the one which is calling multiple times, just add the directive to your app by using 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
        };
      }]);
    
    0 讨论(0)
  • 2021-01-12 14:21

    This also works if you change to angular version 1.1.5

    0 讨论(0)
  • 2021-01-12 14:23

    Found an exact same question:

    AngularJs: controller is called twice by using $routeProvider

    The solution is to add "/" at the end of router url:

    -      when('/res/:id',
    +      when('/res/:id/',
    
    0 讨论(0)
  • 2021-01-12 14:25

    I'm still learning angular and I have experienced this problem, when I wrote the directive and included controllers.

    I hope will help someone as I spent quite some time to see what I did:

    .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}
        })
      ....
    
    0 讨论(0)
提交回复
热议问题