2

Suppose that I've written a web page that requires the user to key in data into forms. Suppose that there are two parts of the page that are completely separate in the DOM, yet are logically related. I need to bind them to a single model.

The first (bad) solution I can think of is to completely restructure the page so that everything to be bound to the model is contained in a single <div> element (or perhaps even put the controller on the <body> element).

Another solution might be to bind the inputs to a object that could be made a member of two different controllers, but that sounds like a bit of a kludge.

Suppose the HTML looks like this:

<input ng-model='data1' />
<div>
    <!-- something complicated -->
</div>
<input ng-model='data2' />
scniro
  • 16,844
  • 8
  • 62
  • 106
Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • 3
    Store your model into a service, and inject it into both of your controllers. That's not a kludge, it's the correct way to do it. – Blackhole May 28 '15 at 22:54
  • 1
    What Blackhole said. Services are singletons in your app, and their data will be consistent across your controllers. – bamboo_inside May 28 '15 at 22:57

1 Answers1

4

You can create a shared service and inject into both controllers. This can be achieved by either the factory or service pattern. See SO post angular.service vs angular.factory for some insight on the difference/similarity between the two.

This is the Angular way to do this. See the AngularJS services docs for more information. A simple example may include...

<div ng-app="app">
    <div ng-controller="ctrlA"></div>
    <div ng-controller="ctrlB"></div>
</div>

app.service('sharedService', [function () {
    this.someValue = 'yo!'
}]);

app.controller('ctrlB', ['$scope', 'sharedService', function($scope, sharedService) {
    console.log(sharedService.someValue) // yo!
}]);

app.controller('ctrlA', ['$scope', 'sharedService', function($scope, sharedService) {
    console.log(sharedService.someValue) // yo!
}]);

JSFiddle Link

Community
  • 1
  • 1
scniro
  • 16,844
  • 8
  • 62
  • 106