angular transfer msg from one controller to the other controller by $scope.$on()

来源:互联网 发布:深圳关键词排名软件 编辑:程序博客网 时间:2024/05/15 17:05

<!--test.htm-->

<html ng-app="app">

<body>  

<div ng-controller="ControllerOne">
   <span>ControllerOne</span> <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerTwo">
    <span>ControllerTwo</span>
    <input ng-model="message" >
</div>

<div >
    <span>my-component</span>
    <my-component ng-model="message"></my-component>
</div>

</body>

<script>  
   var app = angular.module('app', []);

  

app.factory('sharedService', function($rootScope) {
      var sharedService = {};
      sharedService.message = '';
      sharedService.prepForBroadcast = function(msg) {
          this.message = msg;
          this.broadcastItem();
      };
 
      sharedService.broadcastItem = function() {
          $rootScope.$broadcast('myEvent');
      };
 
      return sharedService;
    });
   
   
    app.controller('ControllerOne', ['$scope', 'sharedService',ControllerOne]);
    app.controller('ControllerTwo', ['$scope', 'sharedService',ControllerTwo]);
   
    function ControllerOne($scope, sharedService) {
        $scope.handleClick = function(msg) {
            sharedService.prepForBroadcast(msg);
        };

        $scope.$on('myEvent', function() {
            $scope.message = 'ONE: ' + sharedService.message;
        });
    }
   
    function ControllerTwo($scope, sharedService) {
        $scope.$on('myEvent', function() {
            $scope.message = 'TWO: ' + sharedService.message;
        });
    }
   
    app.directive('myComponent', function(sharedService) {
        return {
            restrict: 'E',
            controller: function($scope, $attrs, sharedService) {
                $scope.$on('myEvent', function() {
                    $scope.message = 'Directive: ' + sharedService.message
                });
            },
            replace: true,
            template: '<input>'
        };
    });

</script>

</html>

 

0 0
原创粉丝点击