Jas
Jas

Reputation: 79

What is the best practice in sharing a scope variable among controllers?

I have an array of variables (I'll call it ArrVar) which is available to all the controllers through a service. This variable has been assigned as a scope variable in CtrlA as $scope.ArrVar. If a user toggles a button under CtrlA, a method attached to CtrlA will make changes to $scope.ArrVar, update the variable in the service, and present the list using ng-repeat.

But I have a totally separate controller, CtrlB, which needs to make changes to the scope variable under CtrlA, which is not available to access from CtrlB.

I can think of two solutions:

  1. a global controller
  2. assign the variable at root scope

but both approaches don't seem to be the best practise. Is there any other elegant way of doing it? Two controllers are totally different, so merging won't do it.

Upvotes: 1

Views: 57

Answers (1)

Dylan
Dylan

Reputation: 4773

If you share the data specific to the obj (like element position data.msg) it will bind with a service with no watching or anything.

2 controllers plunker

app.controller('FirstCtrl', function($scope, Shared) {
  $scope.data = Shared;
})
.controller('SecondCtrl', function($scope, Shared) {
  $scope.data = Shared;
})
.factory('Shared', function() {
  return { msg : ['one','two','three'] }
});

   <div ng-controller="FirstCtrl">
      <input ng-model="data.msg"/>
      {{data}}
   </div>    
   <div ng-controller="SecondCtrl">
      <input ng-model="data.msg"/>
     {{data}}
   </div>

Upvotes: 1

Related Questions