Gururaj Bhandarkar Gururaj Bhandarkar - 4 years ago 100
AngularJS Question

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

Answer Source
.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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download