1

I'm using angular-fullstack to build a single page application, and in one of my controllers I'm trying to assign a user's id to a variable. The code

$scope.getCurrentUser = Auth.getCurrentUser;

returns

function () {
        return currentUser;
}

This works fine for displaying in my view as my angular code can interpret the function and display the user id using {{getCurrentUser()._id}} which I'm assuming evaluates the promise and displays the code to the view.

My question is how do I assign $scope.getCurrentUser = Auth.getCurrentUser; to a variable in my controller? Whenever I do so, I get undefined variables. I've tried:

$scope.getId = Auth.getCurrentUser()._id;
console.log($scope.getId); //undefined

$scope.getId = Auth.getCurrentUser();
console.log($scope.getId._id); //undefined

I've read forum posts like this and this that explain that these methods are meant to be returned the way they are. Another post that is basically the same question as mine, but I'm still confused how to store the user id becuase the answer was hinting it was console.log that was the issue. Any help would be greatly appreciated, thanks.

syymza
  • 679
  • 1
  • 8
  • 23
Troy Griffiths
  • 351
  • 2
  • 7
  • 17
  • This might be because it takes some time for the promise to be evaluated. But your scope is getting updated before it gets resolved. So it is showing undefined. – Chinni May 17 '15 at 22:24
  • In this case, how would I wait for the promise to be evaluated? I've tried using .then() and nesting the function calls, and also putting them in callback functions but to no avail – Troy Griffiths May 17 '15 at 23:59

1 Answers1

0

Try the following and let me know how this works out:

angular.module('yourModuleName').controller('YourController', ['$scope', 'Authentication',
    function($scope, Authentication) {

        var authentication = Authentication;
        $scope.getId = authentication.user._id;

        console.log($scope.getId);

    }
]);

Make sure Authentication is included in your controller.

Tom
  • 734
  • 2
  • 7
  • 27