Passing Variables Between AngularJS Controllers
Passing variables between AngularJS controllers is a common task in application development. One approach is to create a service to share variables across controllers.
Creating a Shared Service
angular.module('myApp', []) .service('sharedProperties', function () { var property = 'First'; return { getProperty: function () { return property; }, setProperty: function(value) { property = value; } }; });
Using the Service
In controllers, inject the shared service:
function Ctrl2($scope, sharedProperties) { $scope.prop2 = "Second"; $scope.both = sharedProperties.getProperty() + $scope.prop2; }
Considerations
For bindings to work across controllers, it's preferable to bind to an object's property rather than a primitive type.
// Avoid using primitive types var property = 'First'; // Use objects var property = { Property1: 'First' };
Example
See [this fiddle](https://jsfiddle.net/philipjohnson/34qhw/) for an example that demonstrates:
Binding to shared values that update the UI as values change
The above is the detailed content of How Can I Effectively Pass Variables Between AngularJS Controllers?. For more information, please follow other related articles on the PHP Chinese website!