angular ¥on $emit $broadcast 的使用

来源:互联网 发布:淘宝店哪家衣服好看 编辑:程序博客网 时间:2024/05/16 06:24
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script></head><body ng-app ="myApp"><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></body><script>var app = angular.module('myApp',[]);app.controller('SelfCtrl', function($scope) {  $scope.click = function () {    $scope.$broadcast('to-child', 'child');    $scope.$emit('to-parent', 'parent');  }});app.controller('ParentCtrl', function($scope) {  $scope.$on('to-parent', function(event,data) {  console.log(event);    console.log('ParentCtrl', data);   //父级能得到值  });  $scope.$on('to-child', function(event,data) {    console.log('ParentCtrl', data);   //子级得不到值  });});app.controller('ChildCtrl', function($scope){  $scope.$on('to-child', function(event,data) {    console.log('ChildCtrl', data); //子级能得到值  });  $scope.$on('to-parent', function(event,data) {    console.log('ChildCtrl', data); //父级得不到值  });});app.controller('BroCtrl', function($scope){    $scope.$on('to-parent', function(event,data) {      console.log('BroCtrl', data);  //平级得不到值    });    $scope.$on('to-child', function(event,data) {      console.log('BroCtrl', data);  //平级得不到值    });  });</script></html>


0 0
原创粉丝点击