formations/javascript/angular/exercices/scope-2/.solution/app.js

77 lines
1.8 KiB
JavaScript

/*
* Énoncé:
*
* Implémenter les contrôleurs MainCtrl, ACtrl et BCtrl afin que les modifications des champs
* dans le controleur MainCtrl soient répliqués dans les champs respectifs de ACtrl et BCtrl,
* et inversement.
*
* Indices:
* - Attention à l'héritage des $scope
* - Penser à l'utilisation de $broadcast, $emit et $watch
*/
var Exo = angular.module('Exo', []);
Exo.controller('MainCtrl', ['$scope', function($scope) {
$scope.numberA = 5;
$scope.numberB = 2;
$scope.$watch('numberA', function(newVal) {
$scope.$broadcast('numberAChanged', {value: newVal});
});
$scope.$watch('numberB', function(newVal) {
$scope.$broadcast('numberBChanged', {value: newVal});
});
$scope.$on('numberAChanged', function(evt, data) {
$scope.numberA = data.value;
});
$scope.$on('numberBChanged', function(evt, data) {
$scope.numberB = data.value;
});
}]);
Exo.controller('ACtrl', ['$scope', function($scope) {
$scope.$watch('numberA', function(newVal) {
$scope.$emit('numberAChanged', {value: newVal});
});
$scope.$watch('numberB', function(newVal) {
$scope.$emit('numberBChanged', {value: newVal});
});
$scope.$on('numberAChanged', function(evt, data) {
$scope.numberA = data.value;
});
$scope.$on('numberBChanged', function(evt, data) {
$scope.numberB = data.value;
});
}]);
Exo.controller('BCtrl', ['$scope', function($scope) {
$scope.$watch('numberA', function(newVal) {
$scope.$emit('numberAChanged', {value: newVal});
});
$scope.$watch('numberB', function(newVal) {
$scope.$emit('numberBChanged', {value: newVal});
});
$scope.$on('numberAChanged', function(evt, data) {
$scope.numberA = data.value;
});
$scope.$on('numberBChanged', function(evt, data) {
$scope.numberB = data.value;
});
}]);