Philip7899
Philip7899

Reputation: 4677

can't get $state to work with angular-ui-router

I am trying to do a simple route redirect using $state. I can't get it to work. Here is my code:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ng-token-auth'])

.run(function($ionicPlatform, $location, $rootScope, $state) {
  $ionicPlatform.ready(function($state) {

    $rootScope.$on('auth:login-success', function($state) {
      console.log('success event triggered yo main');
      // $location.path('main');
      $state.go('main');
    });

  });
})

.config(function($stateProvider, $urlRouterProvider, $authProvider) {
  $stateProvider

  // setup an abstract state for the tabs directive

  .state('main', {
    url: '/main',
    templateUrl: 'templates/main.html'
  })

  .state('home', {
    url: '/home',
    templateUrl: 'templates/home.html'
  })
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/home');

});

This gives me the following error:

ionic.bundle.js:25642 TypeError: $state.go is not a function
    at app.js:28
    at Scope.$broadcast (ionic.bundle.js:29477)
    at ng-token-auth.js:191
    at ionic.bundle.js:23384
    at processQueue (ionic.bundle.js:27879)
    at ionic.bundle.js:27895
    at Scope.$eval (ionic.bundle.js:29158)
    at Scope.$digest (ionic.bundle.js:28969)
    at Scope.$apply (ionic.bundle.js:29263)
    at done (ionic.bundle.js:23676)

I tried removing $state from $rootScope.$on but I got this error:

ionic.bundle.js:25642 TypeError: Cannot read property 'go' of undefined
    at app.js:28
    at Scope.$broadcast (ionic.bundle.js:29477)
    at ng-token-auth.js:191
    at ionic.bundle.js:23384
    at processQueue (ionic.bundle.js:27879)
    at ionic.bundle.js:27895
    at Scope.$eval (ionic.bundle.js:29158)
    at Scope.$digest (ionic.bundle.js:28969)
    at Scope.$apply (ionic.bundle.js:29263)
    at done (ionic.bundle.js:23676)

How do I fix this?

Upvotes: 0

Views: 558

Answers (2)

Abdullah Rasheed
Abdullah Rasheed

Reputation: 3752

Try removing the $state argument from the $rootScope.$on. I think it should be:

$rootScope.$on('auth:login-success', function() {
      console.log('success event triggered yo main');
      // $location.path('main');
      $state.go('main');
});

By passing the $state as an argument you are essentially doing this:

$rootScope.$on('auth:login-success', function($state) {
      var $state;
      console.log('success event triggered yo main');
      // $location.path('main');
      $state.go('main'); //undefined...
});

You may need to it from $ionicPlatform.ready(function($state) {... as well. You are defining the call back functions...not passing in $state. What you think is happening is not.

Upvotes: 1

Lev
Lev

Reputation: 3924

You need to set dependency to ui.router module:

angular.module('starter', ['ionic', .... , 'ui.router'])

Upvotes: 0

Related Questions