$on , $emit , $broadcast , $apply

$scope.$on('事件名称',function(event,data){

  //监听事件

});

$scope.$emit('事件名称','传递的数据');//子元素向父元素发送事件请求,传递数据;

$scope.$broadcast('事件名称','传递的数据');//父元素向子元素发送事件请求,传递数据;

$scope.$apply();//当数据值发送改变时,及时更新数据;

例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body ng-app="firstApp">
    <div ng-controller="MyController">
        <h1>This is the parent scope:{{answer}}</h1>
        <div ng-controller="MyController">
            <h2>This scope inherits from the parent scope</h2>
            This prints '42':{{answer}}
        </div>
    </div>
    <div ng-controller="allEvent">
        接收子元素传递给父元素的值:{{all}}
        <div ng-controller="parentEvent">
            <span ng-click="parentClick()">父级点击,向子级传数据</span>
            <div ng-controller="childEvent">
                它是parentEvent的子级 {{answer}}
            </div>
        </div>
        <div ng-click="clickAll">点击向allEvent发送数据</div>
    </div>
</body>
<script src="common/angular.js"></script>
<script>
    var app=angular.module('firstApp',[]);

    app.controller('MyController',function($scope){
        $scope.answer = 42;
    }).controller('parentEvent',function($scope){
        $scope.parentClick = function (){
            $scope.$broadcast('sendChild',12);
            $scope.$emit('sendAll','你好呀,我是子元素');
        }
    }).controller('childEvent',function($scope){
        $scope.$on('sendChild',function (event , data){
            console.log('child');
            console.log(event);
            console.log(data);
            $scope.answer = data;
        })

    }).controller('allEvent',function($scope){
        $scope.$on('sendAll',function (event , data){
            console.log('child');
            console.log(event);
            console.log(data);
            $scope.all = data;
        })
    })
</script>
</html>

 

转载于:https://www.cnblogs.com/dyy-dida/p/9882403.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值