3
.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

0

2 Answers 2

2

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];
        }
    };
}]);
Sign up to request clarification or add additional context in comments.

Comments

0
.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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.