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);
    });
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM