MarcoS
MarcoS

Reputation: 17721

Angularjs: a factory to share data between controllers

I have an angular.js app with multiple views, and I need to preserve status among view change.
So I use a very simple factory to share data.
And, in the controllers, I use the factory name to use my data, instead of "$scope":

app.factory('share', function() {
  return {};
}

app.controller('FirstCtrl', function ($scope, share) {
  share.obj1['a'] = 'ABC';
});

app.controller('SecondCtrl', function ($scope, share) {
  share.obj1['b'] = 'DEF';
  if (share.obj1['a'] === 'ABC') {
    ...
  }
});

And, my simplified html view is like this:

...
<div ng-repeat="(key, item) in obj1">
  {{item}}
</div>
...

This of course doesn't work, because ng-* directives in views only have access to $scope...

Is it possible to keep my data in sync with share factory using $scope?

Upvotes: 1

Views: 382

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40328

You can just do $scope.share = share at the end of each controller and of course modify the view:

<div ng-repeat="(key, item) in share.obj1">

Alternatively, and if the structure of share is NOT going to change (there is always an obj1), you could do angular.extend($scope, share). This is dangerous if share gets new properties, these will not be seen by the scope, until a new controller is created.

Upvotes: 4

Related Questions