• angular 事件广播和事件监听


    一,angularjs $broadcast $emit $on的处理思想

    在一个controller里面通过事件触发一个方法,在方法里面通过$broadcast$emit来定义一个变量,在父,子controller里面通过$on来获取。

    二,实例说明angularjs $broadcast $emit $on的用法

    <div ng-controller="ParentCtrl">                  //父级  
        <div ng-controller="SelfCtrl">                //自己  
            <a ng-click="click()">click me</a>  
            <div ng-controller="ChildCtrl"></div>     //子级  
        </div>  
        <div ng-controller="BroCtrl"></div>           //平级  
    </div>  

    js代码

    appControllers.controller('SelfCtrl', function($scope) {  
        $scope.click = function () {  
            $scope.$broadcast('to-child', 'child');  
            $scope.$emit('to-parent', 'parent');  
        }  
    });  
    
    appControllers.controller('ParentCtrl', function($scope) {  
        $scope.$on('to-parent', function(d,data) {  
            console.log(data);         //父级能得到值  
        });  
        $scope.$on('to-child', function(d,data) {  
            console.log(data);         //子级得不到值  
        });  
    });  
    
    appControllers.controller('ChildCtrl', function($scope){  
        $scope.$on('to-child', function(d,data) {  
            console.log(data);         //子级能得到值  
        });  
        $scope.$on('to-parent', function(d,data) {  
            console.log(data);         //父级得不到值  
        });  
    });  
    
    appControllers.controller('BroCtrl', function($scope){  
        $scope.$on('to-parent', function(d,data) {  
            console.log(data);        //平级得不到值  
        });  
        $scope.$on('to-child', function(d,data) {  
            console.log(data);        //平级得不到值  
        });  
    });

    点击Click me的输出结果

    child  
    parent

    $broadcast赋的值,只能子级得到值;$emit赋的值,只能父级得到;而平级的什么都不能得到。

  • 相关阅读:
    [leetcode] Combinations
    [leetcode] Search for a Range
    [leetcode] Combination Sum II
    [leetcode] Combination Sum
    [leetcode] Reverse Bits
    [leetcode] Number of 1 Bits
    [leetcode] Longest Substring Without Repeating Characters
    [leetcode] Reverse Words in a String
    [leetcode] Rotate Array
    习题8-3 数组循环右移
  • 原文地址:https://www.cnblogs.com/crazycode2/p/6748966.html
Copyright © 2020-2023  润新知