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

本文探讨了Angular应用中如何通过广播机制实现Controller和组件间的通信,包括使用服务共享状态和监听事件来传递消息的过程。

<!--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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值