日期:2014-05-16  浏览次数:20340 次

AngularJS的$emit和$broadcast实例

$emit和$broadcast使得event、data在controller与view之间的传递变的简单。

  • $emit只能向parent controller传递event与data
  • $broadcast只能向child controller传递event与data

实例代码:
AngularEvent.html

<!DOCTYPE html>
<html>
<head>
    <script src="lib/jquery-1.9.1.js"></script>
    <script src="lib/angular.js"></script>
    <script type="text/javascript" src="js/emit-broadcast.js"></script>
    <style>
        .ng-scope {
            border: 1px dotted red;
        }
    </style>
</head>
<body>
<div ng-app="" class="container">
    <div ng-controller="EventController" class="span12">
        Root scope MyEvent count: {{count}}
        <ul>
            <li ng-repeat="i in [1]" ng-controller="AbcController">
                <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
                <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
                <button ng-click="fireEvent()">fireEvent()</button>
                <br>
                Middle scope MyEvent count: {{count}}
                <ul>
                    <li ng-repeat="item in [1, 2]" ng-controller="EventController">
                        - Leaf scope MyEvent count: {{count}}
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</div>
</body>
</html>

emit-broadcast.js

function EventController($scope) {
    $scope.count = 0;
    $scope.$on('MyEvent', function() {
        $scope.count++;
    });
}

function AbcController($scope) {
    $scope.fireEvent = function() {
        $scope.$emit('MyEvent');
        $scope.$broadcast('MyEvent');
    };
}

运行效果:

刚打开页面

点击“$broadcast('MyEvent')”按钮,发现Leaf scope下的count变化了,每点击一次加1。

?