AngularJs: controller is called twice by using $ro

2019-01-13 02:56发布

Module routes:

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

switchModule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/build-content', {templateUrl: 'build-content.html', controller: BuildInfoController});
}]);

Controller:

function BuildInfoController($http, $scope){
    alert("hello");
}

Html:

<html ng-app="switchModule">
...
<body>
    <ul>
        <li><a href="#build-content"/></a></li>
    </ul>
    <div class="ng-view"></div>
</body>
...

Each time when i click the hyperlink '', the 'BuildInfoController' will be called twice. Am i missing something here?

11条回答
Anthone
2楼-- · 2019-01-13 03:36

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.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-13 03:42

Same Here Mine was a case of having 2 ng-view directives.

enter code here Removed the duplicate i.e. ng-view, fixed it.

查看更多
等我变得足够好
4楼-- · 2019-01-13 03:44

I had face same issue today. I had added controller name in my $routeProvider and also in my html.

$routeProvider
    .when('/login', {
            controller: 'LoginController',
            templateUrl: 'html/views/log-in.html'
     })

and in my view as

<div class="personalDetails" ng-controller="LoginController"> </div>

You can remove controller name either from your view or from your routeprovider.

查看更多
你好瞎i
5楼-- · 2019-01-13 03:45

A controller can be added to more than one element of the DOM, so this problem can occur if this has been done e.g. :

  <div id="myDiv1" ng-controller="myController" ....></div>
  ....
  <div id="myDiv2" ng-controller="myController" ....></div>
查看更多
放荡不羁爱自由
6楼-- · 2019-01-13 03:46

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!

查看更多
劫难
7楼-- · 2019-01-13 03:46

Remove the ng-controller directive from your template pages if exists .

查看更多
登录 后发表回答