mohamed abdul
mohamed abdul

Reputation: 1

angularjs undefined object in service

I want to share data from controller 1 to another controller

I get an undefined error in my 2nd controller. Is anyone able to tell me whats wrong with my code?

Service

app.service('var_transfer_service', function(){
       var test_var;              

          return {
             getVar: function () {
                return test_var;
           },
             setVar: function( _test_var ) {
                test_var = _test_var; 
                console.log(test_var);//show the object content in my console
            }
        }
   })

Controller 1

app.controller('homeCtrl', function($scope,$http, $filter ,var_transfer_service){
$scope.search_item = function ($event,item){
         console.log(item)
         var latt = item.lat;
         var lngt = item.lng;

         var_transfer_service.setVar(item); 
     }       

});

Controller 2

 app.controller('MapCtrl',function($scope,var_transfer_service, $state, $cordovaGeolocation) {
    var transferred_var = var_transfer_service.getVar();
    console.log(transferred_var); //undefined object
 });

Upvotes: 0

Views: 334

Answers (2)

Ron Dadon
Ron Dadon

Reputation: 2706

You used a service, but wrote a factory.

Angular services return the function instance, so put functions on the function scope, using "this".

Using service:

app.service('var_transfer_service', function(){
    var test_var;              
    this.getVar = function () {
        return test_var;
    };
    this.setVar = function( _test_var ) {
        test_var = _test_var; 
        console.log(test_var);//show the object content in my console
    }
}   

Basically, angular service returns the function itself, but factory return the return value of the function - so, you wrote a factory.

So your code would work, if you will use app.factory:

app.factory('var_transfer_service', function(){
       var test_var;              

          return {
             getVar: function () {
                return test_var;
           },
             setVar: function( _test_var ) {
                test_var = _test_var; 
                console.log(test_var);//show the object content in my console
            }
        }
   })

Upvotes: 0

Daniel Bauer
Daniel Bauer

Reputation: 168

It's undefined because it's not initialized:

var test_var;

You only set a value on the setVar function which gets called in the $scope.search_item function in the secound controller (that you never call).

What is your indented behaviour?

Upvotes: 1

Related Questions