0

We are building what will become a big angular application. We already use heavily directives, services and have as many as 14 controllers.

Our problem is to share data between controllers. We would like to be able to share data between controllers that are far away (not siblings) and that would not break the bi-directional binding.

I proposed to use services dedicated to carrying data.

var MyApp = angular.module('MyApp', []);

MyApp.factory('dataContainer', function(){ return {} });
function FirstCtrl($scope, dataContainer) {
    $scope.data = dataContainer;

}

function SecondCtrl($scope, dataContainer) {
    $scope.data = dataContainer;
}

You can try it in the fiddle http://jsfiddle.net/didier_/R2Bgs/2/.

Is that good practice?

user983716
  • 1,992
  • 1
  • 22
  • 32
  • Please look at this SO question http://stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs – Chandermani Mar 07 '13 at 13:18

1 Answers1

2

Using services for that is absolutely a good idea. You don't have to think about such objects as services, that's just the default naming in an Angular project. Once your application grows, you probably end up with factories for different types of objects (state objects as in your example, resource objects, helper objects, etc), and the name "services" becomes a bit too ambiguous.

I'd be cautious about having a raw state object passed around like that though. You should probably wrap access to it in methods/getters and setter to avoid having different parts of your application to overwrite each others state when they shouldn't, which can be a bit of a pain to debug.

Anders Ekdahl
  • 22,685
  • 4
  • 70
  • 59
  • Thanks for your answer! But I see a problem with the getters and setters: the bi-directional binding will be broken. Me too I do not like passing unspecified data-structure around but I can't find a better way to do. – user983716 Mar 07 '13 at 14:55
  • @user983716: "the bi-directional binding will be broken", why would it be broken? It's still the same object, and you can bind method calls in your templates as well. If you mean that you won't be able to use it in `ng-model` then that might be a good thing, since you probably want to filter the input before letting it modify the global application state. – Anders Ekdahl Mar 07 '13 at 15:19
  • You are 100% correct. Thanks a lot! – user983716 Mar 07 '13 at 15:31