When it comes to handling communication between different scopes, there are various approaches to consider. The most suitable method should be selected based on the relationships between the scopes, whether they are in separate templates or modules, and other factors.
One approach is to create a mediator service that can store the necessary value and be injected wherever required - such as in controllers, other services, or directives.
In Module 1 Template 1:
<div ng-controller="Ctrl1">
<input type="text" ng-model="val">{{ val }}
</div>
Module 1 Controller 1:
app.controller('Ctrl1', ['$scope', 'ValMediator', function($scope, ValMediator) {
$scope.val = '';
$scope.$watch(
function(){
return ValMediator.getVal();
},
function(newVal){
$scope.val = newVal;
}
);
$scope.$watch('val',
function(newVal){
ValMediator.setVal(newVal);
}
);
}]);
In Module 2 Template 2:
<div ng-controller="Ctrl2">
<input type="text" ng-model="val">{{ val }}
</div>
Module 2 Controller 2:
app.controller('Ctrl2', ['$scope', 'ValMediator',function($scope, ValMediator) {
$scope.val = '';
$scope.$watch(
function(){
return ValMediator.getVal();
},
function(newVal){
$scope.val = newVal;
}
);
$scope.$watch('val',
function(newVal){
ValMediator.setVal(newVal);
}
);
}]);
Mediator Service:
app.factory('ValMediator', function() {
var val = '';
return {
setVal: function(newVal){
val = newVal;
},
getVal: function(){
return val;
}
};
});
To see an example of this implementation, please refer to the first jsBin example. `ValMediator` demonstrates how a service like this can store and expose variables for use by multiple controllers.
=====================
Another option is to emit events through the `$rootScope`. While this method can facilitate cross-module/scope communication, it may clutter the `$rootScope` with unnecessary events. Nevertheless, it's worth considering as a valid approach.
To see this alternative method, please refer to the second jsBin example.
In Module 1 Controller 1:
app.controller('Ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.val = '';
$scope.$on('Val/update', function(e, arg){
console.log('val update 1', arg);
$scope.val = arg;
});
$scope.$watch('val',
function(newVal, oldVal){
if (newVal === oldVal) return;
$rootScope.$broadcast('Val/update', newVal);
}
);
}]);
In Module 2 Controller 2:
app.controller('Ctrl2', ['$scope', '$rootScope',function($scope, $rootScope) {
$scope.val = '';
$scope.$on('Val/update', function(e, arg) {
console.log('val update 2', arg);
$scope.val = arg;
});
$scope.$watch('val',
function(newVal, oldVal) {
if (newVal === oldVal) return;
$rootScope.$broadcast('Val/update', newVal);
}
);
}]);
This concludes the explanation of the second example, where changes are reacted to and updates are published using event broadcasting via `$rootScope`.