码迷,mamicode.com
首页 > 移动开发 > 详细

$on , $emit , $broadcast , $apply

时间:2018-10-31 13:47:37      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:com   body   click   child   发送   rom   func   comm   highlight   

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

 

$on , $emit , $broadcast , $apply

标签:com   body   click   child   发送   rom   func   comm   highlight   

原文地址:https://www.cnblogs.com/dyy-dida/p/9882403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!