控制器启动两次

时间:2015-12-04 16:39:23

标签: angularjs angularjs-routing angularjs-controller

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

MyApp.js:

display: none != visibility: hidden

LoginController.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'
            });
    }
]);

的index.html:

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
        };
    }
    ]);

的login.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>

2 个答案:

答案 0 :(得分:5)

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

  1. 来自login.html - ng-controller

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

    .when('/Login', {
       controller: 'LoginController',
       templateUrl: 'Login.html'
    })
    
  3. 如何解决?您应该从login.html

    中删除ng-controller属性

答案 1 :(得分:0)

您的模板login.html中不需要ng-controller,因为它位于您的路线中。只需删除它,这应该可以解决问题。