Javascript function returns undefined

Akhilendra

I am getting error. My Javascript function returns undefined while it alert correct within the function. On my 1st controller i am calling like this.

 CustomerService.setName(data.name);

And on Service page like this

service.setName = function(name){ 
  var user = name; 
   alert(user); 
  return user;
}

I am accessing this return value on my 2nd controller like this.

$scope.name = CustomerService.setName(name);

*CustomerService is service name.

taguenizy

Consider using get/set

In your service you can have

app.service("CustomerService", function() {  

    var service = {}; 
    service.setName = function(name){ 
        user = name; 
        // optional return if you feel the need to
    }
    service.getName = function(){
        return user;
    }
    return service;
})

Your current service.setName doesn't persist the name cause it's being stored in a locally variable.

Hope this helps

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related