drivers34 drivers34 - 28 days ago 9
AngularJS Question

AngularJS Share data between Controllers when variable is set on another Controller

I need to share data between two controller (controller A and controller B). I have a service in place to share the data. This works and controllerB can see the value that controllerA sets if I'm setting the value of the shared variable using "ng-model=shared.id" from the view, however; if I set the shared variable inside of the controllerA, then controllerB doesn't see it.

app['controller']('controllerA', ['shared', function(shared){

//ControllerB will not see this for some reason, unless I set
//the value from the view using the ng-model=shared.id attribute.
shared['id'] = "123";

}]);

app['controller']('controllerB', ['shared', function(shared){

this['someId'] = shared['id'];

}]);

Answer

Your code will change the service value without any issues. But the issue is controllerB won't be aware of the value change as there is no $digest cycle called.

When you change the value of $scope model, $digest loop will fire and the change carried forward to controllerB.

You can try as below,

app['controller']('controllerA', ['$scope', 'shared', function($scope, shared){
          $scope.shared = shared;
          //ControllerB will not see this for some reason, unless I set
          //the value from the view using the ng-model=shared.id attribute.
          $scope.shared['id'] = "123";    // This will trigger the $digest cycle

     }]);

     app['controller']('controllerB', ['shared', function(shared){

         this['someId'] = shared['id'];   

     }]);
Comments