Amelia Earheart Amelia Earheart - 6 months ago 9
AngularJS Question

angularJS: undefined variable 'userName'

This is my controller. I have two functions and I'm trying to pass variable available in one function inside the other. But I'm getting an undefined variable error.

I tried declaring variable globally but even after doing that, undefined error exists.
Can any one tell me where did I make mistake?

(function() {

angular
.module('myApp.my', [])

.factory('myService', function($http) {

return {
getUserSessInfo: function() {
return $http.get('getUserInfo.php');
},
getNotifications: function(userName)
{
return $http.get('getMyNotifications.php?username='+userName);
}
};
})

.controller('myController', function($routeParams, myService) {
var vm = this;
var userName;

//To get user session value
myService.getUserSessInfo().success(function(data) {
userName = data.username;
//vm.userName = data.username;
});

//myService.getNotifications(vm.userName).success(function(data) {
myService.getNotifications(userName).success(function(data) {
vm.notifications = data;
});

});
})();

Answer
(function() {

angular
    .module('myApp.my', [])

    .factory('myService', function($http) {

        return {    
            getUserSessInfo: function() {
                return $http.get('getUserInfo.php');
            },
            getNotifications: function(userName) 
            {
                return $http.get('getMyNotifications.php?username='+userName);
            }
        };
    })

    .controller('myController', function($routeParams, myService) {
        var vm = this;
        var userName;

        //To get user session value
        myService.getUserSessInfo().success(function(data) {
            userName    = data.username;
            myService.getNotifications(userName)
            .success(function(data) {
                vm.notifications = data;
                }); 
        });


    });
})();

like the person above mentioned, you need to make sure you have retrieved username from the server before using it inside getNotification() because it is an async call.

I suggest you put this call inside your router resolve block and inject the data (notification) into the controller, that way your username will always be defined. even with my code above, it will be undefined initially until the request from back-end has been completed successfully