1

So, i'm trying to get an object ($rootScope.User) in the NavCtrl after the user signs in (so after the onLogin function runs).

But, i'm doing something wrong and I can't figure out how to fix it. I think it might be reading the code before it gets a value. But, i'm not really sure. If anyone could help me out that would amazing!

Thanks!

.controller('LoginCtrl', function (Backand, $state, $rootScope, LoginService, $ionicPopup, dataService) {

    var login = this;
    $rootScope.isLoggedin = null;

    function signin() {
      LoginService.signin(login.email, login.password)
          .then(function () {
          onLogin();
        }, function (error) {
          console.log(error);

          $rootScope.showAlert = function () {
            var alertPopup = $ionicPopup.alert({
                title: 'Login Error',
                template: error.error_description
              });
          };

          $rootScope.showAlert();
        });
    }

    function onLogin() {
      $rootScope.$broadcast('authorized');
      $state.go('tabs.feed');
      login.username = Backand.getUsername();
      $rootScope.isLoggedin = true;

      $rootScope.cUser = Backand.getUserDetails().$$state.value;
      console.log($rootScope.cUser);
    }
});

.controller('NavCtrl', function($scope, $rootScope, Backand, dataService) {

  function getUser() {
      $scope.user = $rootScope.cUser;
      console.log($scope.user);
    }

  getUser();
});

3 Answers 3

2

Might not be the answer you look for, but avoid using $rootScope to store globals

Use a service and inject it

.factory('UserService', function() {
  return {
      user : {name:'anonymous'}
  };
});

and then in a controller:

.controller('NavCtrl', function($scope, UserService, Backand, dataService) {
    $scope.user = UserService.user;
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's a typo. Remove the cfrom the cUser one line above the console.log($rootScope.User);

OR do this

console.log($rootScope.cUser);

1 Comment

I actually fixed that typo after I posted the question and it still isn't working...
0

When you do this $state.go('tabs.feed') is there a chance that tabs.feed is calling NavCtrl? If so then yes, you're reading it before setting the value.

Comments