. , ..
, . , - , , .
1 1
<div ng-controller="Ctrl1">
<input type="text" ng-model="val">{{ val }}
</div>
1 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);
}
);
}]);
2 2
<div ng-controller="Ctrl2">
<input type="text" ng-model="val">{{ val }}
</div>
2 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);
}
);
}]);
app.factory('ValMediator', function() {
var val = '';
return {
setVal: function(newVal){
val = newVal;
},
getVal: function(){
return val;
}
};
});
, jsBin ValMediator - , val getter . . $scope.$watch , $scope. val .
=====================
- $rootScope. , , rootScope , . / .
jsBin
$rootScope, . , $scope $rootScope :
1 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);
}
);
}]);
2 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);
}
);
}]);
- .