2016-07-28 79 views
0

我想在我的run()中獲取當前狀態名稱。我正在使用$ state.current.name。但它返回空字符串。如何使用angularjs獲取當前狀態名稱

$rootScope.$on('$stateChangeStart', function (event, next) {    
      var json = (function() { 
       event.preventDefault(); 
       $.ajax({ 
        'async': false, 
        'global': false, 
        'url':'users/testLogin', 
        //'data': 'action=showOrders', 
        'dataType': "json", 
        'success': function (data) { 
         if(data.success){ 
          $rootScope.authenticated = true; 
          $rootScope.id = data.data.id; 
          $rootScope.unique_id = data.data.unique_id; 
          $rootScope.print_house_id = data.data.print_house_id; 
          $rootScope.name = data.data.name; 
          $rootScope.email = data.data.email; 
          $rootScope.type = data.data.type; 
         } else { 
          console.log($state.current.name); 

         }       
        } 
       }); 
      })(); 
     }); 

任何人都可以找出我的錯誤在哪裏。

+0

的可能重複:http://stackoverflow.com/questions/23590799/ui-router-get-state-name-from-object-function – varit05

+1

首先,你應該使用有棱角的'$ http'而不是jquery'$ .ajax'在這裏;其次,它看起來並不像你在這個方法中注入'$ state'。另外,像這樣使用'$ rootScope'是一種反模式。 – Claies

回答

1

使用此,

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { 

     $state.current = toState; // if you need the target Url 
      $state.current = fromState;// If you need the current URL 
     var json = (function() { 
      event.preventDefault(); 
      $.ajax({ 
       'async': false, 
       'global': false, 
       'url':'users/testLogin', 
       //'data': 'action=showOrders', 
       'dataType': "json", 
       'success': function (data) { 
        if(data.success){ 
         $rootScope.authenticated = true; 
         $rootScope.id = data.data.id; 
         $rootScope.unique_id = data.data.unique_id; 
         $rootScope.print_house_id = data.data.print_house_id; 
         $rootScope.name = data.data.name; 
         $rootScope.email = data.data.email; 
         $rootScope.type = data.data.type; 
        } else { 
         console.log($state.current.name);//It should show value now 

        }       
       } 
      }); 
     })(); 
    }) 
+0

'$ state'是由ui-router提供的一項服務,不應該有必要手動設置它的任何值..... – Claies

+0

@Claies我已經更新了我的答案。你是對的。但我手動設置,因爲它不清楚他需要哪個州名。 – Ved

+0

如果您手動設置值,則應該使用不同的變量名稱,以免將此值與該名稱的服務合法提供的值混淆。 – Claies