1. 程式人生 > >$on , $emit , $broadcast , $apply

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