how do return the $state.current.name from ui-router statechange

前端 未结 4 1492
野性不改
野性不改 2020-12-28 13:49

I would like to return the .state(\'name\') when I change location in angular.

From my run() it can return the $state object:

相关标签:
4条回答
  • 2020-12-28 14:33

    You can listen for '$stateChangeSuccess' and set state accrodingly. For example -

    $rootScope.$on('$stateChangeSuccess',
      function(event, toState, toParams, fromState, fromParams) {
        $state.current = toState;
      }
    )
    
    0 讨论(0)
  • 2020-12-28 14:38

    If you want to console your state in the controller then you should console like that:

    console.log($state.current.name);
    

    And if you want to console it in views then:

    In controller :

    $scope.state = $state.current.name;
    

    In Template: print like that

    {{state}}
    
    0 讨论(0)
  • 2020-12-28 14:44

    As an alternative to Sandeep's solution, you can also do it this way:

    angular.module('yourApp').run(['$rootScope', '$state',
        function ($rootScope, $state) {
            $rootScope.$state = $state;
        }
    ]);
    

    Doing it this way, it only gets set once instead of on every stateChange. Basically you just store a reference to $state somewhere - I chose $rootScope just to keep this example simple.

    Now in my code I can easily reference it like:

    <div ng-show="$state.includes('accounting.dashboard')"></div>
    

    and

    <div>Current State: {{$state.current.name}}</div>
    

    I also generally store $stateParams as well so I have even more information about the state (but I left it out of this example).

    0 讨论(0)
  • 2020-12-28 14:53

    You can also try.

    .controller('yourApp', function($scope,$state) {
      $scope.state = $state;
    

    Now you can log it in your console.

    console.log($state);
    

    It should return the current state you are in.

    Or you can call the scope in your html view like this.

    {{state.current.name}}
    

    It will also return de state you are in.

    0 讨论(0)
提交回复
热议问题