控制器启动两次

Controller gets initiated twice

我有一个简单的控制器 (logincontroller),它在加载时启动两次 login.html,但我不知道为什么会这样。

MyApp.js:

angular.module('PVM', [
    'Authentication',
    'Modal',
    'ngRoute'
])
.config([
    '$routeProvider', function($routeProvider) {
        $routeProvider
            .when('/Login', {
                controller: 'LoginController',
                templateUrl: 'Login.html'
            })
            .when('/Home', {
                controller: 'ModalController',
                templateUrl: 'Home.html'
            })
            .otherwise({
                redirectTo: '/Login'
            });
    }
]);

LoginController.js:

angular.module("Authentication")
.controller("LoginController",
[
    "$scope", "$rootScope", "$location", "AuthenticationService",
    function($scope, $rootScope, $location, AuthenticationService) {
        AuthenticationService.ClearCredentials();

        $scope.login = function() {

            var foo = "bar"; //Breakpoint hits here twice when loading login.html
        };
    }
    ]);

index.html:

<!DOCTYPE html>
<html ng-app="PVM">
<head>
<title>My Ang</title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<link href="Content/bootstrap-theme.min.css" rel="stylesheet" />
<link href="Content/MyCss.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

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


<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-route.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-cookies.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap-tpls.min.js"></script>


<script src="Scripts/Services/ModalService.js"></script>
<script src="Scripts/Services/AuthenticationService.js"></script>
<script src="Scripts/Controller/LoginController.js"></script>
<script src="Scripts/Controller/ModalController.js"></script>
<script src="Scripts/MyApp.js"></script>


</body>
</html>

Login.html:

<div class="container centeredDiv" ng-controller="LoginController">
    <p>Login page</p>
</div>

因为你的控制器在 2 个地方执行。

  1. 来自 login.html - ng-controller

    <div class="container centeredDiv" ng-controller="LoginController">
        <p>Login page</p>
    </div>
    
  2. 来自与路由关联的控制器 - /Login

    .when('/Login', {
       controller: 'LoginController',
       templateUrl: 'Login.html'
    })
    

如何解决?您应该从 login.html

中删除 ng-controller 属性

您的模板中不需要 ng-controller login.html,因为它在您的路由中。只需将其删除即可。