-1

I want to access variable from another controller any body help

My code

app.controller('MapCtrl',function($scope, $state, $cordovaGeolocation) {
    $scope.search_item = function($event,item){
        console.log(item);
        var lat = item.lat;
        var lng = item.lng;      
    }
});

to

app.controller("homeCtrl", function($scope,$http, $filter ){

});

1 Answers1

0

You can set up a service that 'shares' the variable between the two controllers.

Create a file: services.js in the app/ directory (where app.js is located)

   angular.module('app.services', [])

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

          return {
             getVar: function () {
                return test_var;
           },
             setVar: function( _test_var ) {
                test_var = _test_var;
            }
        }
   })

Now inject this service into the controllers that need variable sharing:

app.controller('MapCtrl',function($scope, $state, $cordovaGeolocation, var_transfer_service) {
  $scope.search_item = function($event,item){
    console.log(item);
    var lat = item.lat;
    var lng = item.lng;

    var_transfer_service.setVar(lat);       
  }
});

app.controller("homeCtrl", function($scope,$http, $filter, var_transfer_service ){
   var transferred_var = var_transfer_service.getVar();    
   // transferred_var will now equal 'lat' from the other controller
});

You can further modify the function definitions in services.js and function calls in your controllers to accommodate more variables.

Make sure to also add the services.js module to your app:

angular.module('app', ['ionic', 'app.controllers', 'app.services'])
  • it set value and i can read it n the console but in getVar it undifined,,,,help pls – mohamed abdul Jun 19 '16 at 18:21
  • If there is a page refresh occurring between the time you set the variable and try getting it again, it won't work and will be undefined. The service does not store data through page refreshes. You could use local storage to save the data temporarily if needed. –  Sep 21 '16 at 03:08