Want to pass variables between controllers in AngularJS? One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.
Simple service example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | angular.module('myApp', []) .service('sharedProperties', function () { var property = 'First'; return { getProperty: function () { return property; }, setProperty: function(value) { property = value; } }; }); |
Using the service in a controller:
1 2 3 4 | function Ctrl2($scope, sharedProperties) { $scope.prop2 = "Second"; $scope.both = sharedProperties.getProperty() + $scope.prop2; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.