smanhoff
smanhoff

Reputation: 466

AngularJS: access scope in other function in same controller

I am using angular in a project and after the user logs in his data gets saved into the database and he can pass on to the main application. BUT I need to use his name in order to show his orders, so I can extract his name when he logs in but when I want to use this name in another function I get: 'undefined'...?

AngularJS

$scope.redirectafterLogin = function($username)
{
    $rootScope.username = $username;
    window.location = "index1.html";
}
//SHOW ORDER FOR LOGGED IN CUSTOMER  
$scope.orderCustomer = function (){
    $http.get('/api/getorderS/'+$rootScope.username).then(function (results) 

    {  
    ... 
    }

So how can I access the $rootScope.username variable in my orderCustomer function?

Upvotes: 0

Views: 295

Answers (1)

Guinn
Guinn

Reputation: 1385

You could save the username in a service. A $scope or $rootScope is whiped when doing a full refresh, because when you 'instantiate' the controller a scope is created, when you refresh the page the controller gets re-instantiated and thus the scope is whiped aswell. So to create your service do something like:

app.factory('userService', [function() {
    return {
        userName: null
    }
}])

and then in your controller:

app.controller('loginCtrl', ['userService', function(userService) {
    $scope.redirectafterLogin = function($username)
    {
        userService.userName = $username;
        window.location = "index1.html";
    }

    $scope.orderCustomer = function (){
       $http.get('/api/getorderS/'+ userService.userName).then(function (results) 

       {  
            ... 
       }

You could make a getter and setter to beautify above code aswell, just add:

setUserName: function(user) {
        this.userName = user;
     },
getUserName: function() {
        return this.userName;
}

to your service, and then replace the + userService.username with + userService.getUserName()

edit On a side note: make sure you are using ng-controller="loginCtrl" in 'index1.html'!

Upvotes: 1

Related Questions