AngularJs: controller is called twice by using $routeProvider

前端 未结 10 2200
慢半拍i
慢半拍i 2020-12-04 14:43

Module routes:

var switchModule = angular.module(\'switchModule\', []);

switchModule.config([\'$routeProvider\', function($routeProvider) {
    $routeProvid         


        
相关标签:
10条回答
  • 2020-12-04 15:10

    I too had a similar problem with a customDirective and unitentionally duplicated my controller.

    <html>
       <body ng-app="MyApp" ng-controller="MyDirectiveCtrl">
          <my-directive></my-directive>
       </body>
    </html>
    
    angular.directive('myDirectivie', [function() {
       return {
             restrict: 'E',
             controller: 'MyDirectiveCtrl',
    
             ...
    
       }
    }]);
    

    I resolved it by removing ng-controller tag at body level

    0 讨论(0)
  • 2020-12-04 15:11

    Mine was a case of having 2 ng-view directives. I tried to wrap it, but unintentionally duplicated it:

    <div class="ng-view">
        <div ng-view></div>
    </div>
    

    Removed the wrapper, fixed it.

    0 讨论(0)
  • 2020-12-04 15:11

    I had same problem and found that if you bootstrapped you angular two time you can have same error.

    In my case I had <body ng-app> but also angular.bootstrap(document,['app']) and that caused double initialization of controllers.

    Hope this can save some time to someone.

    0 讨论(0)
  • 2020-12-04 15:13

    I've had a similar problem. I found adding a trailing slash in the route but not in the link worked as expected.

    $routeProvider.
    when('/build-content/',...);
    

    With this markup

    <li><a href="/build-content">Content</a></li>
    

    And then AngularJS will correct the URL in the browser to what is defined in the $routeProvider.

    Bizarrely the opposite seems to work too with a trailing slash in the link and not in the route. It seems as long as the trailing slashes don't match the resolves and controller won't be called twice!

    0 讨论(0)
提交回复
热议问题