formations/javascript/angular/scope-3.md

866 B

.cadoles-slide-title[L'objet $scope (3/4)]

Communication inter-controlleurs, évènements & propagation

<html>
  <body ng-app="myApp">

    <div ng-controller="ParentCtrl">
      <div ng-controller="ChildCtrl">
      </div>
    </div>

    <script src="angular.js"></script>
    <script>
      var myApp = angular.module('myApp', []);

      myApp.controller('ParentCtrl', ['$scope', function($scope) {

        $scope.$on('child-event', function(evt) { console.log('Emitted event: ', evt); });
        $scope.$broadcast('parent-event', {data: 'Parent event !'});

      }]);

      myApp.controller('ChildCtrl', ['$scope', function($scope) {

        $scope.$emit('child-event', {data: 'Child event !'});
        $scope.$on('parent-event', function(evt) { console.log('Broadcasted event: ', evt); });

      }]);

    </script>
  </body>
</html>