Home >Web Front-end >JS Tutorial >How Can I Effectively Share Variables Between Unrelated AngularJS Controllers?
Passing Variables Between AngularJS Controllers
In AngularJS, managing data flow between controllers can be challenging, especially when they're not nested. Here's how you can achieve variable sharing across controllers:
Using Services
Services are a powerful way to share data among components. Create a service and inject it into the controllers that need access to the shared variables:
angular.module('myApp') .service('sharedProperties', function () { var property1 = 'First'; return { getProperty1: function () { return property1; }, setProperty1: function(value) { property1 = value; } }; });
In your controller, inject the service and use its methods to access and modify shared variables:
function Ctrl2($scope, sharedProperties) { $scope.prop2 = 'Second'; $scope.both = sharedProperties.getProperty1() + $scope.prop2; }
Binding to Shared Values
For real-time updates of shared values across controllers, you can bind to an object's property instead of a primitive type:
angular.module('myApp') .service('sharedProperties', function () { return { property1: { Property1: 'First' } }; });
In your controller, bind to the object's property instead of the primitive value:
function Ctrl2($scope, sharedProperties) { $scope.prop2 = 'Second'; $scope.both = sharedProperties.property1.Property1 + $scope.prop2; }
Tips:
The above is the detailed content of How Can I Effectively Share Variables Between Unrelated AngularJS Controllers?. For more information, please follow other related articles on the PHP Chinese website!