1:先通过关键字 $emit(" 变量名 "); 向父级控制器传输事件。
PS:emit会自动按照HTML的结构寻找父级的controller。
2:父级通过关键字 $scope.$on ("$emit变量名",function(){$scope.$broadcast("向下广播变量名");});
PS:父级先收到子控制器的请求,然后通过关键字$broadcast定义一个向下的广播名,开始向下广播。
3:需要接收广播的子控制器,依然用 $scope.$on(" 广播名 ",function(){ }); 接广播然后进行处理。
<!doctype html>
<html ng-app = "myapp">
<head>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-controller = "Test">
<h1>{{text}}</h1>
<div ng-controller = "TestOne">
<h2>{{one}}</h2>
</div>
<div ng-controller = "TestTow">
<h3>{{Two}}</h3>
</div>
<div ng-controller = "TestThree">
<h4>{{Three}}</h4>
<buttom ng-click = "Call()">点击传输</buttom>
</div>
</div>
</body>
<script>
var app = angular.module('myapp', []);
app.controller("Test", function($scope){
$scope.text = "顶层默认值";
$scope.$on ("CallTest",function(){
$scope.$broadcast("CallNext");
});
});
app.controller("TestOne", function($scope){
$scope.one = "第一个默认值";
$scope.$on ("CallNext",function(){
$scope.one = "收到顶部数据更新要求"
});
});
app.controller('TestTow', function($scope){
$scope.Two = "第二个默认值";
$scope.$on ("CallNext",function(){
$scope.Two = "我也收到顶部数据更新要求"
});
});
app.controller('TestThree', function($scope){
$scope.Three = "第三个默认值";
$scope.Call = function(){
$scope.Three = "开始向顶层传输!"
$scope.$emit("CallTest");
};
});
</script>
</html>
网友评论