angularjs1.x.x通信

监听事件

$scope.$on("someEvent", function(event, data) {
    // 这里取到发送过来的数据 data
});

1. 父组件 => 子组件

Controller 往子 Controller 上发送事件(从作用域往下发送事件),使用scope.$broadcast

$scope.$broadcast("someEvent", {});

2. 子组件 => 父组件

Controller 往父 Controller 上发送事件(从作用域往上发送事件),使用scope.$emit

$scope.$emit("someEvent", {});

以下例子为父->子以及子->父的事件传播

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://cdn.bootcss.com/angular.js/1.5.8/angular.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="Controller as ctrl" >
        接受消息次数: {{count}}
        <button ng-click="sendMsg($event)">发消息给子控制器</button>
        <div ng-controller="ChildController as childCtrl" >
            接受消息次数: {{count}}       
            <button ng-click="sendMsg($event)">发消息给父控制器</button>
        </div>          
    </div>                                                                               
    <script type="text/javascript" >        
        angular.module("myApp", []).controller("Controller", function($scope) {
            $scope.count = 0;
            $scope.sendMsg = function() {
                $scope.$broadcast("addChildCount");
            }           
            $scope.$on("addParentCount", function() {
                console.log("addCount in parent");
                $scope.count++;     
            }); 
        }).controller("ChildController", function($scope) {
            $scope.count = 0;  
            $scope.sendMsg = function() {
                $scope.$emit("addParentCount");
            }       
            $scope.$on("addChildCount", function() {
                console.log("addChildCount in child");
                $scope.count++; 
            });         
        });                                                                                               
    </script>   
</body>     
</html>                  

3. 组件A = > 兄弟组件B

借助$rootScope广播实现。

.controller('innerCtrlA', ['$scope', '$rootScope', function($scope, $rootScope){
    $scope.change = function(){
        // 广播事件
        $rootScope.$broadcast('nameChanged', $scope.name);
    }
    $rootScope.$on('nameChanged', function(event, data){
        $scope.name = data;
    })
}])
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容