0

我是 angularjs 的新手,我正在尝试使用这个 generator-angular-fullstack,

我想要页面登录而不是主页面,我使用代码,我的解决方案是在 MainCtrl 中添加'authenticate:true'

angular.module('myapp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('main', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainCtrl',
        authenticate: true
      });
  }); 

并注释“event.preventDefault();”行 在 app.js 中的 run 函数中

.run(function ($rootScope, $location, Auth) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$stateChangeStart', function (event, next) {
      Auth.isLoggedInAsync(function(loggedIn) {
        if (next.authenticate && !loggedIn) {
          //event.preventDefault();
          $location.path('/login');
        }
      });
    });

但我不确定这种变化是好的还是有其他最佳解决方案。

4

1 回答 1

1

为此,您的代码将是这样的

main.js中

 angular.module('myapp')  
       .config(function ($stateProvider) {
        $stateProvider
          .state('main', {
            url: '/main',
            templateUrl: 'app/main/main.html',
            controller: 'MainCtrl'
          });   
      });

account.js中

    angular.module('myapp')
      .config(function ($stateProvider) {
        $stateProvider
          .state('login', {
            url: '/',
            templateUrl: 'app/account/login/login.html',
            controller: 'LoginCtrl'
          })
          .state('signup', {
            url: '/signup',
            templateUrl: 'app/account/signup/signup.html',
            controller: 'SignupCtrl'
          })
          .state('settings', {
            url: '/settings',
            templateUrl: 'app/account/settings/settings.html',
            controller: 'SettingsCtrl',
            authenticate: true
          });
      });

login.controller.js

angular.module('myapp')
  .controller('LoginCtrl', function ($scope, Auth, $location, $window) {
    $scope.user = {};
    $scope.errors = {};

    $scope.login = function(form) {
      $scope.submitted = true;

      if(form.$valid) {
        Auth.login({
          email: $scope.user.email,
          password: $scope.user.password
        })
        .then( function() {
          // Logged in, redirect to home
          $location.path('/main');
        })
        .catch( function(err) {
          $scope.errors.other = err.message;
        });
      }
    };

    $scope.loginOauth = function(provider) {
      $window.location.href = '/auth/' + provider;
    };
  });
于 2015-12-03T13:43:35.313 回答