Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 613
Gururaj Bhandarkar Avatar asked Apr 21 '26 13:04

Gururaj Bhandarkar


1 Answers

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];
        }
    };
}]);
like image 57
Ameya Deshpande Avatar answered Apr 24 '26 03:04

Ameya Deshpande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!