概念
- $emit,$broadcast设置值,$on获取值
- $emit向上传递,$broadcast向下传递
EXAMPLE
- html
<pre>
<div ng-controller="ParentController">
parentCount:{{ count }}
<div ng-controller="CurentController">
<button type="button" ng-click="emit()">emit</button>
<button type="button" ng-click="broadcast()">broadcast</button>
curentCount:{{ count }}
<div ng-controller="ChildController">
childCount:{{ count }}
</div>
</div>
<div ng-controller="BorController">
borCount:{{ count }}
</div>
</div>
</pre> - js
<pre>
// 父级controller
.controller('ParentController', function($scope) {
$scope.count = 0;
$scope.$on('p-count', function(d, data){
console.log(data); // emit中保存的值
$scope.count ++;
})
})
// 使用$emit,$broadcast保存值,可以在父级,子级和本身中取得
.controller('CurentController', function($scope) {
$scope.count = 0;
$scope.emit = function(){
$scope.count ++;
// 向父级controller传递值p-count
$scope.$emit('p-count', $scope.count);
}
$scope.broadcast = function(){
$scope.count = $scope.count + 1;
// 可以不传第二个args,$on获取时,第二个参数为undefined
$scope.$broadcast('c-count');
}
})
.controller('ChildController', function($scope){
$scope.count = 0;
$scope.$on('c-count', function(d,data){
console.log(data); // undefined
$scope.count ++
})
})
// 兄弟controller,不会被影响
.controller('BorController', function($scope) {
$scope.count = 0;
// 下面两个不被触发,回调函数不执行,不输出任何东西
$scope.$on('p-count', function(d,data){
console.log(data);
})
$scope.$on('c-count', function(d,data){
console.log(data);
}
})
</pre>