Ela Buwa
Ela Buwa

Reputation: 1704

Get current state in ionic app

Newbie to the whole ionic and angular scene. I used the ionic creator to generate the view files. My goal is to check if the user is logged in before proceeding in to a tab. However, before getting to the authentication part, I wanted to check which window the user is on. I am trying to use a simple alert/console.log to identify the progress.

Below is my code.

.controller('adminPageCtrl', ['$scope', '$stateParams', '$state', function     ($rootScope, $scope, $stateParams, $state) {
    //alert($state.current.name);
    $scope.currState = $state;
    var currentState = $state.current.name; 
    console.log($state);
}])

I have come across the below error which i cant seem to make heads or tails. "ionic.bundle.js:26799 TypeError: Cannot read property 'current' of undefined".

Any help is greatly appreciated. Even the console.log($state); command returns "undefined".

Upvotes: 0

Views: 6860

Answers (2)

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3645

You've need $rootScope dependency. Without them you will receive another list of arguments.

.controller('adminPageCtrl', ['$rootScope', '$scope', '$stateParams', '$state', function($rootScope, $scope, $stateParams, $state) {
    $scope.currState = $state;
    var currentState = $state.current.name; 
    console.log($state);
}])

Upvotes: 1

igor.araujo
igor.araujo

Reputation: 1007

The problem with your code is that you are defining more depencencies than you are actually using.

You can either fix it by removing the reference to $rootScope on the function definition or adding it to the list of dependencies.

.controller('adminPageCtrl', ['$scope', '$stateParams', '$state', function($scope, $stateParams, $state) {
   //alert($state.current.name);
   $scope.currState = $state;
   var currentState = $state.current.name; 
   console.log($state);
}])

OR

.controller('adminPageCtrl', ['$rootScope', '$scope', '$stateParams', '$state', function($rootScope, $scope, $stateParams, $state) {
   //alert($state.current.name);
   $scope.currState = $state;
   var currentState = $state.current.name; 
   console.log($state);
}])

And since you are using the name of the dependencies to name the variables inside the function, you could also use Implicit Annotation (please take a look on the docs https://docs.angularjs.org/guide/di):

.controller('adminPageCtrl', function($scope, $stateParams, $state) {
   //alert($state.current.name);
   $scope.currState = $state;
   var currentState = $state.current.name; 
   console.log($state);
})

Upvotes: 2

Related Questions