You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<!DOCTYPE html><htmlng-app="wsscat"><head><metacharset="UTF-8"><title></title></head><scripttype="text/javascript" src="js/angular.js"></script><bodyng-controller="bodyCtrl"><articleng-controller="indexCtrl">
{{name}}
<buttonng-click="click()">Ok</button><sectionng-controller="indexChildCtrl"><inputng-model="name" ng-change="changName()" />
{{name}}
</section></article><articleng-controller="indexBrotherCtrl">
{{name}}
</section></article></body><script>varapp=angular.module('wsscat',[]);app.controller('bodyCtrl',function($scope){$scope.$on('to-parent',function(event,data){console.log('I am the parent, I got it',data);});})app.controller('indexCtrl',function($scope){$scope.name="wsscat";$scope.click=function(){//向下广播事件$scope.$broadcast('to-child','haha');//向上广播事件$scope.$emit('to-parent','hehe');}//子控制器indexChildCtrl改变名字后,向上发送to-parent-name事件委托告诉indexCtrl,$scope.name值已经发生改变,并一起作出改变$scope.$on('to-parent-name',function(event,data){console.log('I am the parent to-parent-name, I got it',data);$scope.name=data;});})app.controller('indexChildCtrl',function($scope){$scope.$on('to-child',function(event,data){console.log('I am the child, I got it',data);});$scope.changName=function(){$scope.$emit('to-parent-name',$scope.name);}})app.controller('indexBrotherCtrl',function($scope,$rootScope){$rootScope.$on('to-parent',function(event,data){console.log('I am the parent from $rootScope, I got it',data);$scope.name=data;});})app.service("hiEventService",function($rootScope){this.broadcast=function(){$rootScope.$broadcast("hi")}this.listen=function(callback){$rootScope.$on("hi",callback)}})</script></html>
上面的结果,当我们按下按钮,indexCtrl分别向它的父于子进行消息传递,打印信息如下
The text was updated successfully, but these errors were encountered:
发送事件可以用
向父控制器传递信息
$scope.$emit('name', 'args');
或者是
向子控制器传递信息
$scope.$broadcast('name', 'args');
name:事件的名字
args:事件所需要传递的参数
接受事件可以用(仅此一个方法可以接受事件)
例子如下
注意
bodyCtrl为indexCtrl的父
indexChildCtrl为indexCtrl的子
上面的结果,当我们按下按钮,indexCtrl分别向它的父于子进行消息传递,打印信息如下
The text was updated successfully, but these errors were encountered: