1

首先,我只是 angularJS 的初学者。我有这些文件

应用程序.js

'use strict';

var app = angular.module('testApp', [
  'ngRoute',
  'ngCookies'
])

app.config(['$routeProvider',
  function($routeProvider) {

    $routeProvider
      .when('/login', {
        controller: 'LoginController',
        templateUrl: '../app/login/login.html',
        hideMenus: true
      })

    .when('/main', {
        templateUrl: '../app/main/main.html',
        controller: 'MainController'


      })
      .when('/sales', {
        controller: 'SalesController',
        templateUrl: '../sales/sales.html',
        hideMenus: true
      })
      .otherwise({
        redirectTo: '/login'
      });
  }
])

.run(['$rootScope', '$location', '$cookieStore', '$http',
  function($rootScope, $location, $cookieStore, $http) {
    // keep user logged in after page refresh
    var checkStorage;
    if ($cookieStore.get('testToken') != null) {
      checkStorage = $cookieStore.get('testToken');
    } else if (sessionStorage.testToken!= null) {

      checkStorage = $.parseJSON(sessionStorage.testToken);
    }
    $rootScope.globals = checkStorage || {}
    $rootScope.$on('$locationChangeStart', function(event, next, current) {
      // redirect to login page if not logged in
      if ($location.path() !== '/login' && !$rootScope.globals.username) {

        $location.path('/login');
      } else if ($location.path() == '/login' && $rootScope.globals.username) {

        $location.path('/main');
      }
    });
  }
]);

索引.html

<!DOCTYPE html>
  <meta name="viewport" content="width=device-width, user-scalable=no">

<html ng-app="testApp">
<head>
    <meta charset="utf-8" />
    <title>testApp</title>
    <link rel="stylesheet" href="content/bootstrap.min.css" />
     <link rel="stylesheet" href="content/main.css" />
</head>
<body>


 
                <div ng-view style="height:100%"></div>
 
    <script src="scripts/jquery-2.1.3.min.js"></script>
    <script src="scripts/bootstrap.min.js"></script>
    <script src="scripts/angular.js"></script>
    <script src="scripts/angular-route.js"></script>
    <script src="scripts/angular-cookies.js"></script>
    <script src="app/app.js"></script>
    <script src="app/login/login.controller.js"></script>
    <script src="app/login/login.service.js"></script>
    <script src="app/main/main.controller.js"></script>


</body>

</html>

登录.html

<div class="login-form">
<div ng-show="error" class="alert alert-danger login-error">{{error}}</div>
<div class="login-box">
<!--ui-keypress="{13:'login()'} && form.$valid"-->
<form name="form"  ng-submit="login()" role="form" class="form-signin">
    <div class="form-group">
        <div class="center logo"></div>
        
        <input type="text" name="username" id="username" class="form-control login-text" ng-model="username" placeholder="Username" required />
        <span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>

       
        <input type="password" name="password" id="password" class="form-control login-text" ng-model="password"  placeholder="Password" required />
        <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
    <div style="padding-left:5px;padding-top:2px;"><input id="chkRemember" type="checkbox" ng-model="remember" /> Remember Me</div>
    </div>
  
     <div class="">
        <button type="submit" ng-disabled="form.$invalid || dataLoading" class="btn">Login</button>
     </div>
     
</form>
</div>
</div>

login.controller.js

'use strict';

angular.module('testApp')

.controller('LoginController', ['$scope', '$rootScope', '$location', 'AuthenticationService',
  function($scope, $rootScope, $location, AuthenticationService) {
    // reset login status
    AuthenticationService.ClearCredentials();
    $scope.login = function() {
      $scope.dataLoading = true;
      var rem = 0;
      if ($scope.remember) {
        var rem = 1
      }
      AuthenticationService.Login($scope.username, $scope.password, rem, function(response) {

        if (response.success) {

          AuthenticationService.SetCredentials($scope.username, response.token, rem);
          $location.path('/main');



        } else {
          $scope.error = response.message;
          $scope.dataLoading = false;
        }
      });
    };
  }
]);

登录服务.js

'use strict';

angular.module('testApp')
  .factory('AuthenticationService', ['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
    function(Base64, $http, $cookieStore, $rootScope, $timeout) {
      var service = {};

      service.Login = function(username, password, remember, callback) {



        $http.post('api/test/log', {
            username: username,
            password: Base64.encode(password),
            remember: remember
          })
          .success(function(response) {

            callback(response);

          });

      };

      service.SetCredentials = function(username, token, rem) {


        $rootScope.globals = {

          username: username,
          token: token

        };

        if (rem == 1) {
          $cookieStore.put('testToken', $rootScope.globals);
        } else {
          sessionStorage.setItem("testToken", JSON.stringify($rootScope.globals));

        }
      };

      service.ClearCredentials = function() {
        $rootScope.globals = {};
        $cookieStore.remove('testToken');

      };

      return service;
    }
  ])

.factory('Base64', function() {
  /* jshint ignore:start */

  var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=AA';

  return {
    encode: function(input) {
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;

      do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }

        output = output +
          keyStr.charAt(enc1) +
          keyStr.charAt(enc2) +
          keyStr.charAt(enc3) +
          keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
      } while (i < input.length);

      return output;
    },

    decode: function(input) {
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;

      // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
      var base64test = /[^A-Za-z0-9\+\/\=]/g;
      if (base64test.exec(input)) {
        window.alert("There were invalid base64 characters in the input text.\n" +
          "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
          "Expect errors in decoding.");
      }
      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

      do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
          output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
          output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

      } while (i < input.length);

      return output;
    }
  };

  /* jshint ignore:end */
});

主控制器.js

'use strict';

angular.module('testApp')

.controller('MainController', ['$scope', '$cookieStore', '$http',
  function($scope, $cookieStore, $http) {
    var session;
    console.log('LOOPING CONTROLLER');
    if ($cookieStore.get('testToken') != null) {

      session = $cookieStore.get('testToken');
    } else {
      session = $.parseJSON(sessionStorage.testToken);

    }
   

    $scope.remove = function() {
      $cookieStore.remove('testToken');
      sessionStorage.removeItem("testToken");
    }
  }

]);

根据给定的文件,index.html 正确显示 login.html 并且没有错误。但是,在登录并且 login.controller.js 中的 $location.path 执行时,路由启动并运行 main.controller.js 只是为了在我的浏览器上的页面检查器中看到垃圾邮件 console.log('LOOPING CONTROLLER') 并且没有在模板中加载 main.html。

我错过了什么吗?谢谢您的帮助

更新

我似乎与 jQuery 有冲突。删除 jquery 使页面工作正常,除了解析。对导致冲突的原因有任何想法吗?

4

1 回答 1

0

我猜问题出$location.path('/main');在您的处理程序中的调用$locationChangeStart。鉴于此处理程序在位置更改之前执行,它看起来会无限执行。

于 2015-03-02T08:32:00.587 回答