Akhilendra yadav Akhilendra yadav - 1 year ago 181
AngularJS Question

Javascript function returns undefined

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


And on Service page like this

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

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

$scope.name = CustomerService.setName();

*CustomerService is service name.

Answer Source

Consider using get/set

In your service you can have

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

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

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download