Angularjs – $state.go(‘state.name’) not correctly changing states

angular-ui-routerangularjs

I am attempting to move between states (using ui.router) programmatically without the user having to click on anything. The documentation at http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state seems to indicate that I can do this with $state.go('state.name') except that I'm having trouble making this work.

I've created a plunkr to demonstrate my issue. The state should ideally be switching to show "Success" rather than "Failure" when it's run. If you look at the console, it'll say that it cannot read the property 'go' of undefined. How else can I go about changing the state programmatically?

Thanks!

http://plnkr.co/edit/MSLbKaKzmuXPud7ZcKqs

Edit: more clearly specifying that I'm using ui.router

Best Answer

2 things:

  1. You forgot to inject $state into your app.run()
  2. Use $stateChangeSuccess instead

    .run(['$rootScope','$state', function($rootScope, $state) { $rootScope.$on('$stateChangeSuccess', function(event, next) { $state.go('root.other'); })}]);

Working plunk.

Related Topic