How can I pass some data from one controller to another peer controller [duplicate]
I have the following two peer controllers. There's no parent to these:
<div data-ng-controller="Controller1">
</div>
<div data-ng-controller="Controller2">
The value of xxx is: {{ xxx }}
</div>
angular.module('test')
.controller('QuestionsStatusController1',
['$rootScope', '$scope'
function ($rootScope, $scope) {
// How can I set the value of xxx in the HTML that's part of Controller2
}]);
angular.module('test')
.controller('QuestionsStatusController2',
['$rootScope', '$scope',
function ($rootScope, $scope) {
}]);
In controller 1 I want to update the value of the variable xxx in the HTML that's controlled by Controller2. Is there a way I can do this?
Solution 1:
Use a service to achieve this:
MyApp.app.service("xxxSvc", function () {
var _xxx = {};
return {
getXxx: function () {
return _xxx;
},
setXxx: function (value) {
_xxx = value;
}
};
});
Next, inject this service into both controllers.
In Controller1, you would need to set the shared xxx value with a call to the service: xxxSvc.setXxx(xxx)
Finally, in Controller2, add a $watch on this service's getXxx() function like so:
$scope.$watch(function () { return xxxSvc.getXxx(); }, function (newValue, oldValue) {
if (newValue != null) {
//update Controller2's xxx value
$scope.xxx= newValue;
}
}, true);
Solution 2:
Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).
http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp
Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU
var testModule = angular.module('testmodule', []);
testModule
.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.service('myservice', function() {
this.xxx = "yyy";
});