In AngularJS, you can share data between controllers using a service. Services act as singletons, meaning they maintain their state throughout the application's lifetime, and they are the ideal way to share data and functionality between different components, such as controllers.
Here's how you can update a service variable in one controller and use the updated value in another controller:
Create a Shared Service: First, create a shared service using the
factory
orservice
method of your AngularJS module. The service will hold the shared data and methods to update and access that data.javascript// app.js angular.module('myApp', []) .factory('sharedDataService', function() { var data = { sharedVariable: '' }; return { getData: function() { return data.sharedVariable; }, setData: function(newValue) { data.sharedVariable = newValue; } }; });
Inject the Shared Service in Controllers: Inject the shared service into the controllers where you want to use the shared data.
javascript// controller1.js angular.module('myApp') .controller('Controller1', function($scope, sharedDataService) { // Update the shared data from Controller1 $scope.updateSharedData = function() { sharedDataService.setData('Updated value from Controller1'); }; });
javascript// controller2.js angular.module('myApp') .controller('Controller2', function($scope, sharedDataService) { // Access the shared data from Controller2 $scope.sharedData = sharedDataService.getData(); });
Update the Data in Controller1: In
Controller1
, you can call thesetData()
method of the shared service to update the shared variable's value.Access the Updated Data in Controller2: In
Controller2
, you can call thegetData()
method of the shared service to access the updated value of the shared variable.
Remember that the service acts as a singleton, so the updated value will persist across different controllers throughout the application's lifetime.
Finally, make sure that your controllers are declared within the same AngularJS module (myApp
in this example) to ensure they have access to the shared service.
By using a shared service to manage shared data, you can easily update a variable in one controller and use the updated value in another controller within your AngularJS application.