Gururaj Bhandarkar
Gururaj Bhandarkar

Reputation: 292

How to get data dynamically from one controller to another in angularjs?

.controller('Ctrl1', function($scope, $http) {

  $scope.langChecked = function(){
   $scope.value = $('input[name=lang-check]:checked').val();
    console.log($scope.value);
  };
})

.controller('Ctrl2', function($scope, $http, $state, Scopes) {
    if($scope.value='something'){
         alert('scope passed');
    }
});

i tried using rootscope and passing values between controllers

.run(function ($rootScope) {
    $rootScope.$on('scope.stored', function (event, data) {
        console.log("scope.stored", data);
    });
})
.factory('Scopes', function ($rootScope) {
    var mem = {};

    return {
        store: function (key, value) {
            $rootScope.$emit('scope.stored', key);
            mem[key] = value;
        },
        get: function (key) {
            return mem[key];
        }
    };
});

but my ctrl2 page loads first on refresh and it gives error when i use

Scopes.get('Ctrl1').value;

in Ctrl2. Please help

Upvotes: 3

Views: 478

Answers (2)

Brave Soul
Brave Soul

Reputation: 3620

you have to inject your factory with $rootscope.

Factories don't have access to the current controller/directive scope because there isn't one. They do have access to the root of the application though and that's why $rootScope is available

.factory('Scopes',["$rootScope", function ($rootScope) {
    var mem = {};

    return {
        store: function (key, value) {
            $rootScope.$emit('scope.stored', key);
            mem[key] = value;
        },
        get: function (key) {
            return mem[key];
        }
    };
}]);

Upvotes: 2

Gururaj Bhandarkar
Gururaj Bhandarkar

Reputation: 292

.factory('Authorization', function() {
  authorization = {};
  authorization.variable= '';
  return authorization;
})

.controller('Ctrl1', function($scope, Authorization) {
  $scope.input = Authorization;
  console.log($scope.input.variable);
})

.controller('Ctrl2', function($scope, Authorization) {
  $scope.input = Authorization;
  console.log($scope.input.variable);
 });

<input data-ng-controller="Ctrl1" type="text" ng-model="input.variable">

This worked for me. Thank you for your answers :) I was using ionic with angular. using just factory to store data and fetch worked like a charm.

Upvotes: 0

Related Questions