how do return the $state.current.name from ui-router statechange
Solution 1
You can listen for '$stateChangeSuccess' and set state accrodingly. For example -
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
$state.current = toState;
}
)
Solution 2
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).
Solution 3
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.
Armeen Moon
I am a generalist; slowly becoming a specialist in Web Development. I mix art, design, and technology, to create effective experiences that deliver value at scale. My professional goals are simple: surround myself with smart, energetic, creative people while working on solving problems that matter. Specialties: Functional and Object Oriented JavaScript ,Angular+, AngularJS, AWS, CSS/SCSS, Vector/DOM motion graphics, semantic HTML, NodeJS, Golang, and passionate about learning i18n/l10n, a11y, and modern web workflow.
Updated on January 20, 2020Comments
-
Armeen Moon over 4 years
I would like to return the
.state('name')
when I change location in angular.From my
run()
it can return the$state
object:.run(function($rootScope, Analytics, $location, $stateParams, $state) { console.log($state);
but when I try to get
$state.current
it is empty object.run(function($rootScope, $location, $stateParams, $state) { console.log($state.current);
config example:
.config(function($stateProvider, $urlRouterProvider, AnalyticsProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', views: { '': { templateUrl: 'views/main.html', controller: 'MainCtrl' }, 'navigation@home': { templateUrl: 'views/partials/navigation.html', controller: 'NavigationCtrl' }, 'weekly@home': { templateUrl: 'views/partials/weekly.html', controller: 'WeeklyCtrl' }, 'sidepanel@home': { templateUrl: 'views/partials/side-panel.html', controller: 'SidePanelCtrl' }, 'shoppanel@home': { templateUrl: 'views/partials/shop-panel.html', controller: 'ShopPanelCtrl' }, 'footer@home': { templateUrl: 'views/partials/footer.html', controller: 'FooterCtrl' } } })