ajmajmajma
ajmajmajma

Reputation: 14226

Use factory to share information between controllers

I want to share information between controller and I cannot seem to figure out how. I have a set of radios with the model of radioSelect, when i have a certain one selected I want something in another controller to ng-hide. I know this may seem pretty simple, but I'm new to angular, any help would be much appreciated!!

Here is my attempt:

.factory("sessionCheck", function() {

    var sessionCheck={};

 sessionCheck.update = function (index) {

  sessionCheck = index;
  return sessionCheck;

 };

I set up a factory and injected the dependencies into the 2 controllers, the 1 controller has a function on ng-change for the radios to send the value (which works fine with the update). However it would much nice if i could somehow just share the radios model information so i dont have to change (it is constantly listening). The end result should be if the "weeks" selection is selected in the radios an item in another controller which is injected by this factory. So it would be ideal if there was some kind of stream between the 2 controllers that listens to the radios.

Thanks!!

Upvotes: 0

Views: 52

Answers (2)

Simon Trewhella
Simon Trewhella

Reputation: 2484

You're redefining the sessionCheck variable every update with

sessionCheck = index;

Which means there is no update function on that object any more.

Just return the update function so you can use sessionCheck as a service. It will be the same sessionCheck since services in angular are all singletons.

Eg.

.factory("sessionCheck", function() {

var sessionCheck={};

var update = function (index) {

sessionCheck = index; return sessionCheck;

};

return { update: update }

}

Upvotes: 0

Ricardo Mogg
Ricardo Mogg

Reputation: 589

I'm not sure if this answers your question. But if you want to share a variable you could use $rootScope. You can see the documentation here https://docs.angularjs.org/api/ng/service/$rootScope

Upvotes: 1

Related Questions