2016-07-28 81 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