Akhilendra yadav Akhilendra yadav - 2 months ago 20
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.

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();


*CustomerService is service name.

Answer

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

Comments