• angularJS 事件广播与接收


    发送消息: $scope.$emit(name, data) 或者 $scope.$broadcast(name, data);

    接收消息: $scope.on(name,function(event,data){ });

    区别: $emit 广播给父controller   $broadcast 广播给子controller

    broadcast 是从发送者向他的子scope广播一个事件。

    这里就是ParentController发送, ParentController 和 ChildController 会接受到, 而MainController是不会收到的

    $emit 广播给父controller,父controller 是可以收到消息

    $on 有两个参数function(event,msg)  第一个参数是事件对象,第二个参数是接收到消息信息

    var app = angular.module('onBroadcastEvent', ['ng']);
    
    app.controller('MainController', function($scope) {
        $scope.$on('To-MainController', function(event,msg) {
            console.log('MainController received:' + msg);
        });
    });
    
    app.controller('ParentController', function($scope) {
        $scope.click = function (msg) {
            $scope.$emit('To-MainController',msg + ',from ParentController to MainController');
            $scope.$broadcast('To-ChildController', msg + ',from ParentController to ChildController');
            $scope.$broadcast('To-BrotherController', msg + ',from ParentController to BrotherController');
        }
    });
    
    app.controller('ChildController', function($scope){
        $scope.$on('To-ChildController', function(event,msg) {
            console.log('ChildController received:' + msg);
        });
    });
    
    app.controller('BrotherController', function($scope){
        $scope.$on('To-BrotherController', function(event, msg) {
            console.log('BrotherController received:' + msg);
        });
    });
  • 相关阅读:
    March 13 2017 Week 11 Monday
    March 12 2017 Week 11 Sunday
    March 11 2017 Week 10 Saturday
    March 10 2017 Week 10 Friday
    Mrach 9 2017 Week 10 Thursday
    March 8 2017 Week 10 Wednesday
    玩转Sketch,不容错过的5大实用插件推荐
    网页设计排版中哪些元素最重要?
    5 个关键点!优化你的 UI 原型设计
    如何制作一个完美的错误提示信息
  • 原文地址:https://www.cnblogs.com/zcynine/p/5170361.html
Copyright © 2020-2023  润新知