0

I know that there are plenty of ways to share data between controllers in Angular. e.g. snooping prototypical data from parent scope, notifying controllers by scope events, shared services etc.

But what is the idiomatic way to share data for all controllers in a view?

I've read this post: Share data between controllers in AngularJS

Is this the way to go? resolve loaded data upfront and then share the result?

Community
  • 1
  • 1
Roger Johansson
  • 22,764
  • 18
  • 97
  • 193
  • 1
    What do you mean by all controllers in a view? What do you mean by view? It sounds like you're looking for a service though – Peter Ashwell Jan 23 '15 at 09:57

2 Answers2

0

You can write directives contain controller inside and isolated scope with two-way binding variable that you want to share

js:

(function() {
  var app = angular.module('myApp', []);

  app.controller('main',['$scope', function($scope) {
    $scope.sharedVar = 1;
  }]);
  app.directive('dOne', function() {
    return {
      scope: {
        sharedVar: '='
      },
      controller: ['$scope',function($scope) {
        $scope.changeVar = function(val) {
          $scope.sharedVar = val;
        }
      }],
      template: "<div>controller1<button ng-click='changeVar(3)'>clickMe!</button> value: {{sharedVar}}</div>"
    };
  });

  app.directive('dTwo', function() {
    return {
      scope: {
        sharedVar: '='
      },
      controller: ['$scope',function($scope) {
        $scope.changeVar = function(val) {
          $scope.sharedVar = val;
        }
      }],
      template: "<div>controller2<button ng-click='changeVar(2)'>clickMe!</button> value: {{sharedVar}}</div>"
    };
  });
})();

html

<body ng-app="myApp" ng-controller='main'>
    <d-one shared-var="sharedVar"></d-one>
    <d-two shared-var="sharedVar"></d-two>
  </body>

plunker

another option is to use $parent scope plunker using $parent scope

szapio
  • 998
  • 1
  • 9
  • 15
0

I ended up using resolve on my router, so initial values are resolved upfront and then readily available for all controllers.

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193