angularJS 系列(六)---$emit(), $on(), $broadcast()的使用

下面以一个例子来讲述 angular 中的event system,有$emit(), $on(), $broadcast().效果图如下

下面的代码中,用到了 controller AS 的语法,具体这种语法的使用情况,好处或是与 原来 直接在 Controller中把视图对象直接绑定到 $scope 对象上面的区别,

可以查看我之前的一片博文。

直接贴代码

<!DOCTYPE html>
<html>
<head>
    <link  rel="stylesheet" href="css/bootstrap.min.css" />
    <link  rel="stylesheet" href="css/custom.css" />
</head>
<body ng-app="app">

    <div class="container" ng-controller="AccountController as vm">
        <div class="header clearfix">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation">
                        <span>Current Balance: {{ vm.accountBalance | currency }}</span>
                    </li>
                </ul>
            </nav>
            <h3 class="text-muted">Account Controller</h3>
			<h5>dispatches event <b>WithdrawalNotAllowed</b> downwards to Child Controllers using <b>$broadcast</b></h5>

        </div>
        <div class="row">
            <div class="col-lg-6" ng-controller="DepositController as t">
                <h3>Deposit Controller</h3>
				<h5>dispatches event <b>AmountDeposited</b> upwards to AccountController using <b>$emit</b></h5>
                <p>
                    <input type="text" class="form-control" ng-model="t.amount" />
                </p>
                <p>
                    <input type="button" class="btn btn-primary btn-sm" value="Deposit" ng-click="t.deposit()" />
                </p>
            </div>

            <div class="col-lg-6" ng-controller="WithdrawController as vm">
                <h3>Withdraw Controller</h3>
				<h5>dispatches event <b>AmountWithdrawn</b> upwards to AccountController using <b>$emit</b></h5>
                <p>
                    <input type="text"  class="form-control" ng-model="vm.amount" />
                    <span class="error" ng-if="vm.validationError">{{vm.validationError}}</span>
                </p>
                <p>
                    <input type="button" class="btn btn-primary btn-sm" value="Withdraw" ng-click="vm.withdraw()" />
                </p>
            </div>
        </div>

    </div>

    <!--<script type="text/javascript" src="js/jquery.min.js"></script>-->
    <!--<script type="text/javascript" src="js/bootstrap.min.js"></script>-->
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/custom.js"></script>
    <script type="text/javascript" src="app/app.js"></script>
</body>
</html>

  

(function(){
    ‘use strict‘;
    angular.module(‘app‘, [])
        .controller(‘AccountController‘, function($scope){
            var vm = this;
            vm.accountBalance = 0;
            vm.activate = _activate;

            function _activate(){
                $scope.$on("AmountDeposited", _amountDepositedHandler);
                $scope.$on(‘AmountWithdrawn‘, _amountWithdrawnHandler);
            }
            function _amountDepositedHandler(event, args){
                vm.accountBalance += eval(args.amount);
            }
            function _amountWithdrawnHandler(event, args) {
                if (vm.accountBalance - eval(args.amount) < 0) {
                    $scope.$broadcast("WithdrawalNotAllowed", {balance: vm.accountBalance});
                }
                else {
                    vm.accountBalance -= eval(args.amount);
                }
            }
            _activate();
        })
        .controller(‘DepositController‘, function($scope){

            var vm = this;
            vm.amount = 0;
            vm.deposit = _deposit;
            $scope.name = ‘ysr‘;
            function _deposit() {
                alert(this.name);
                $scope.$emit("AmountDeposited", {amount: vm.amount});
                vm.amount = 0;
            }
            console.log(this);
        })
        .controller(‘WithdrawController‘, function($scope){
            var vm = this;
            vm.amount = 0;
            vm.validationError = "";
            vm.activate = _activate;
            vm.withdraw = _withdraw;

            function _activate() {
                $scope.$on("WithdrawalNotAllowed", _withdrawalNotAllowedHandler);
            }

            function _withdraw() {
                vm.validationError = "";
                $scope.$emit("AmountWithdrawn", {amount: vm.amount});
                vm.amount = 0;
            }

            function _withdrawalNotAllowedHandler(event, args) {
                vm.validationError = "You cannot withdraw more than $" + args.balance;
            }

            _activate();
        });

})();
/*(function () {
    ‘use strict‘;

    angular
        .module(‘app‘, [])
        .controller(‘AccountController‘, AccountController)
        .controller(‘DepositController‘, DepositController)
        .controller(‘WithdrawController‘, WithdrawController);

    AccountController.$inject = [‘$scope‘];
    function AccountController($scope) {
        var vm = this;
        vm.accountBalance = 0;
        vm.activate = _activate;

        function _activate() {
            $scope.$on("AmountDeposited", _amountDepositedHandler);
            $scope.$on("AmountWithdrawn", _amountWithdrawnHandler);
        }

        function _amountDepositedHandler(event, args) {
            vm.accountBalance += eval(args.amount);
        }

        function _amountWithdrawnHandler(event, args) {
            if (vm.accountBalance - eval(args.amount) < 0) {
                $scope.$broadcast("WithdrawalNotAllowed", {balance: vm.accountBalance});
            }
            else {
                vm.accountBalance -= eval(args.amount);
            }
        }

        _activate();
    }

    DepositController.$inject = [‘$scope‘];
    function DepositController($scope) {
        var vm = this;
        vm.amount = 0;
        vm.deposit = _deposit;

        function _deposit() {
            $scope.$emit("AmountDeposited", {amount: vm.amount});
            vm.amount = 0;
        }
    }

    WithdrawController.$inject = [‘$scope‘];
    function WithdrawController($scope) {
        var vm = this;
        vm.amount = 0;
        vm.validationError = "";
        vm.activate = _activate;
        vm.withdraw = _withdraw;

        function _activate() {
            $scope.$on("WithdrawalNotAllowed", _withdrawalNotAllowedHandler);
        }

        function _withdraw() {
            vm.validationError = "";
            $scope.$emit("AmountWithdrawn", {amount: vm.amount});
            vm.amount = 0;
        }

        function _withdrawalNotAllowedHandler(event, args) {
            vm.validationError = "You cannot withdraw more than $" + args.balance;
        }

        _activate();
    }
})();*/

  参考:http://www.ezzylearning.com/tutorial/angularjs-event-notification-system-broadcast-emit-and-on-functions

时间: 2024-08-04 19:01:28

angularJS 系列(六)---$emit(), $on(), $broadcast()的使用的相关文章

深究angularJS系列 - 第二弹

深究angularJS系列 - 第二弹,在初步了解了Angular的基础上,进一步的针对Angular的控制器和作用域问题深入探究O(∩_∩)O~~ Angular控制器 控制器(Controller)的理解 控制器是对view的抽象,用来接收view的事件,响应view的请求: 控制器包含view的静态属性和动态的方法: 控制器与view是一对一的关系. 控制器(Controller)的结构 1 .controller("控制器的名字",function($scoppe){ 2 ..

深究angularJS系列 - 第三弹

深究angularJS系列 - 初识 深究angularJS系列 - 第二弹 深究angularJS系列 - 第三弹,我们一起深入探究angular的服务和自定义指令O(∩_∩)O~~ Angular服务 $http: $http是angular中的一个核心服务; $http利用浏览器的xmlhttprequest或JSONP与远程HTTP服务器进行交互; $http的支持多种method的请求,get.post.put.delete.jsonp等. 下面通过JSONP方法进行$http服务的使

AngularJS系列之总结

AngularJS深入的系列就是这九篇博客了,把我以前在项目中应用到的和自己学习的都总结在了里面.为了更方便的看,把我写的AngularJS系列的博客都列到下面.之后就开始学习ionic:html5移动开发框架,它是基于AngularJS的移动开发框架.希望大家多多关注我的博客,多多推荐. AngularJS之站在jQuery的肩膀上: http://www.cnblogs.com/xuema/p/4335180.html AngularJS应用开发思维之1:声明式界面  http://www.

[AngularJS] AngularJS系列(2) 中级篇之路由

目录 原理 angular-route ui-router 事件 深度路由 原理 ng的route本质是监听hashchange事件. 在angular-route中 $rootScope.$on('$locationChangeStart', prepareRoute); $rootScope.$on('$locationChangeSuccess', commitRoute); 在ui-router中 listener = listener || $rootScope.$on('$locat

[转载]去掉的URL里的#号——angularjs系列

AngularJS体验式编程系列文章,将介绍如何用angularjs构建一个强大的web前端系统.angularjs是由Google团队开发的一款非常优秀web前端框架.在当前如此多的web框架下,angularjs能脱颖而出,从架构设计上就高人一等,双向数据绑定,依赖注入,指令,MVC,模板.Angular.js创新地把后台技术融入前端开发,扫去jQuery一度的光芒.用angularjs就像写后台代码,更规范,更结构化,更可控. 关于作者 张丹(Conan), 程序员Java,R,PHP,J

AngularJS系列-翻译官网

公司之前一直用的Web前台框架是Knockout,我们通常直接叫ko,有看过汤姆大叔的KO系列,也有在用,发现有时候用得不太顺手.本人是会WPF的,所以MVVM也是比较熟悉的,学ko也是很快就把汤姆大叔的文章系列看完了,但是ko有时候会有意想不到的问题,同事也有这样的反应,所以就度娘了一下.就找到了AngularJS和KO的对比文章<從Knockout到AngularJS>,看了之后不明觉厉.其实早在AngularJS刚刚问世的那年,因为我订阅了博友--梦想天空(山边小溪)的博客(这里得特别感

深究angularJS系列 - 初识

AngularJS是什么?概念?特征?优点?缺点?那都不是事,话不多说,直接搞起O(∩_∩)O~~ 安装 1.官网http://angularjs.org/下载安装 2.开源库http://www.bootcdn.cn/下载安装 3.bower(一种包管理器)下载安装 bower install angular MVC MVC即"模型 - 视图 - 控制器"的简称,一种设计模式,MVC的从逻辑上将代码清晰地分割为三层,这样可以对每个部分进行独立开发.测试和维护. 模型/Model -

angularJS 系列(一)

angularJS 中 $scope 的原型 和 原型继承之间的细微差别是什么? 参考:http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs The API Reference Scope page says: A scope can inherit from a parent scope. The Dev

[angularjs] angularjs系列笔记(一)简介

Angularjs通过新的属性和表达式扩展了html Andularjs 可以构建一个单一页面的应用程序(SPAS SinglePageApplications) Angularjs通过指令扩展了html,通过表达式绑定数据到html ng-app指令定义Angularjs的应用程序 ng-model指令绑定元素值到应用程序 ng-bind指令把应用程序数据绑定到html视图 <div ng-app=""> <input type="text" n