2017-01-30 71 views
0

我正在使用ui.router來檢測Angular App中的狀態更改。但是控制器不會在加載時被調用。ui.router狀態不按預期方式工作

以下是我的app.js的代碼。

var admin = angular.module('admin',['admin.core']); 
    angular.module('admin.core', ['ui.router', 'satellizer', 'ngMaterial']); 

    admin.config(function($mdThemingProvider, $stateProvider, 
          $urlRouterProvider, $authProvider, $locationProvider){ 
    $mdThemingProvider.theme('default').primaryPalette('light-blue', { 
     'default': '700', 
     'hue-1' : 'A200', 
    }).accentPalette('blue'); 

    // Satellizer configuration that specifies which API route the JWT should be retrieved from 
    $authProvider.loginUrl = '/api/authenticate'; 

    // Redirect to the auth state if any other states are requested other than users 
    $urlRouterProvider.otherwise('/admin/login'); 
    console.log($stateProvider) 
    $stateProvider 
     .state('login', { 
      url: '/admin/login', 
      name: 'login', 
      controller: 'AuthController as auth', 
     }) 
     .state('users', { 
      url: '/admin/users', 
      controller: 'UserController as user' 
     }); 
     $locationProvider.html5Mode(true); 
    }); 

    admin.controller('AuthController', AuthController); 

    function AuthController($auth, $state, $scope) { 
    console.log("Called"); 
    var vm = this; 

    vm.login = function() { 
     var credentials = { 
      email: vm.email, 
      password: vm.password 
     } 
     console.log(credentials); 
     // Use Satellizer's $auth service to login 
     $auth.login(credentials).then(function(data) { 
      // If login is successful, redirect to the users state 
      $state.go('users', {}); 
     }); 
    } 

    } 

AuthController當我的狀態是login不叫。

+0

爲什麼url:'users',而不是'/ users'?並添加名稱:'用戶' –

+0

@PiotrPęczek..更正 – Gags

+0

你有'ui-view'在你的根app html的某個地方嗎? – devqon

回答

1

使用$locationProvider.html5Mode(true);時,您必須提供基準href位置。它會將您的狀態解析網址解析爲http://localhost:8001/admin/#/login,並且應該解決您的問題。

嘗試將<base href="/" />添加到主索引文件的<head />部分,以指定應用程序的基本路徑。

https://docs.angularjs.org/api/ng/provider/$locationProvider

還提供您的服務器上.htaccess文件八方通重定向到郵件索引頁面的具體要求。你可能必須調整它適合你的結構。

<IfModule mod_rewrite.c> 
    RewriteEngine On 
    RewriteBase/
    RewriteRule ^index.html$ - [L] 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule . /index.html [L] 
</IfModule> 

注意mod_rewrite的有我的Apache服務器上啓用。通過 默認它被禁用。

+0

因爲我在管理員,所以我的基地址將是''對嗎?它只有第一次..意味着如果我訪問'http:// localhost:8001/admin'那麼stateprovider使它'http:// localhost:8001/admin/login',但現在如果我將使用刷新那麼Controller不會被調用... – Gags

+0

因此,這可以解決您最初的問題?現在在'F5'/頁面刷新時會出現新問題?正確? –

+0

您是否已將「.htaccess」添加到您的服務器?查看上面更新的答案。 –