Communication between Angular Controllers
In AngularJS, facilitating communication between controllers is often necessary. However, accessing variables from one controller within another poses a challenge when the controllers are not nested.
Passing Variables without Inheritance
Passing the first controller (Ctrl1) as an argument to the second controller (Ctrl2) using $scope, Ctrl1 is not viable due to undefined errors. Similarly, inheriting properties from Ctrl1 to Ctrl2 using Ctrl2.prototype = new Ctrl1(); is also unsuccessful.
Solution: Utilizing Services
To share variables across controllers without nesting, the effective solution is to create a service and inject it into all relevant controllers. A service is an Angular component that can be injected into multiple controllers or directives to share functionality.
Example Service:
angular.module('myApp').service('sharedProperties', function() { var property = 'First'; return { getProperty: function() { return property; }, setProperty: function(value) { property = value; } }; });
Usage in Controllers:
function Ctrl1($scope, sharedProperties) { sharedProperties.setProperty('New First'); } function Ctrl2($scope, sharedProperties) { $scope.prop2 = 'Second'; $scope.both = sharedProperties.getProperty() + $scope.prop2; }
By injecting the sharedProperties service into both controllers, the shared data can be accessed and modified independently.
Binding to Shared Values
In addition to accessing shared values, it is also possible to bind to them in the controller's scope. To retain the bound reference, it is recommended to bind to an object's property instead of a primitive type.
var property = { Property1: 'First' }; // Binded to a static copy in Ctrl1 $scope.prop11 = property.Property1; // Binded to the shared value in Ctrl2 $scope.prop12 = sharedProperties.getProperty().Property1;
The above is the detailed content of How Can AngularJS Controllers Communicate Without Nesting?. For more information, please follow other related articles on the PHP Chinese website!