An AngularJS controller manages the data that is used with its associated HTML views. In some cases, there is a need for several controllers to share some common data. The common data can be user, security or settings that are needed to enable some access or configuration to elements on the view. For other cases, we may need to share data in different controllers to complete a process.
To see this in action, we can create a simple order system which works like a wizard and collects customer and food information. Each view on this demo is managed by a different controller.
Code:
Controllers are stateless and the data that is used by the controller is initialized every time it is loaded. To address this, we need a service that can be injected into the different controllers and can maintain the information. In AngularJS, a service is a singleton which only gets instantiated one time during the life cycle of the module. This allows us to maintain and share information across the initialization of different controllers.
In our demo, the svcAppData services persists the data that is captured from the user in each view.
Service Model:
this.detail = { name: '', dish: '', drink: '' };
Each controller accesses this information via the service detail model. This is done by the following statement:
ctrl.order = svcAppData.detail;
The views bind to the information by using the ng-model directive as shown below:
<input class="form-control" ng-model="ctrl.order.name" placeholder="enter name" type="text">
As the user enters the information, the data field in the model (detail) gets updated with the new information.
I hope this article is able to provide some clarity on how to use services and share data across controllers.