1

First off, I am just a beginner at angularJS. I have these files

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

Index.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>

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

login.service.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 */
});

main.controller.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");
    }
  }

]);

Based on the given files, the index.html displays the login.html correctly and with no errors. however upon login and the $location.path in login.controller.js executes, routing initiates and runs main.controller.js only to see in my the page inspector on my browser spams the console.log('LOOPING CONTROLLER') and doesnt load main.html in the template.

Did I miss anything? thanks for the help

UPDATE

I seem to have conflict with jQuery. Removing jquery makes the pages work fine except for the parsing. Any idea on what is causing the conflict?

4

1 に答える 1

0

問題はハンドラーでの$location.path('/main');呼び出しだと思います。このハンドラーが場所が変わる前$locationChangeStartに実行されることを考えると、無限に実行されるように見えます。

于 2015-03-02T08:32:00.587 に答える