We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it. Service : app. service('setGetData', function() { var data = ''; getData: function() { return data; }, setData: function(requestData) { data = requestData; } });
You can't inject controllers into one another.
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);
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";
});
In one controller, you can do:
$rootScope.$broadcast('eventName', data);
and listen to the event in another:
$scope.$on('eventName', function (event, data) {...});
You need to use
$rootScope.$broadcast()
in the controller that must send datas. And in the one that receive those datas, you use
$scope.$on
Here is a fiddle that i forked a few time ago (I don't know who did it first anymore
http://jsfiddle.net/patxy/RAVFM/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With