监听事件
$scope.$on("someEvent", function(event, data) {
// 这里取到发送过来的数据 data
});
1. 父组件 => 子组件
父 Controller
往子 Controller
上发送事件(从作用域往下发送事件),使用scope.$broadcast
$scope.$broadcast("someEvent", {});
2. 子组件 => 父组件
子 Controller
往父 Controller
上发送事件(从作用域往上发送事件),使用scope.$emit
$scope.$emit("someEvent", {});
以下例子为父->子以及子->父的事件传播
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.bootcss.com/angular.js/1.5.8/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="Controller as ctrl" >
接受消息次数: {{count}}
<button ng-click="sendMsg($event)">发消息给子控制器</button>
<div ng-controller="ChildController as childCtrl" >
接受消息次数: {{count}}
<button ng-click="sendMsg($event)">发消息给父控制器</button>
</div>
</div>
<script type="text/javascript" >
angular.module("myApp", []).controller("Controller", function($scope) {
$scope.count = 0;
$scope.sendMsg = function() {
$scope.$broadcast("addChildCount");
}
$scope.$on("addParentCount", function() {
console.log("addCount in parent");
$scope.count++;
});
}).controller("ChildController", function($scope) {
$scope.count = 0;
$scope.sendMsg = function() {
$scope.$emit("addParentCount");
}
$scope.$on("addChildCount", function() {
console.log("addChildCount in child");
$scope.count++;
});
});
</script>
</body>
</html>
3. 组件A = > 兄弟组件B
借助$rootScope
广播实现。
.controller('innerCtrlA', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.change = function(){
// 广播事件
$rootScope.$broadcast('nameChanged', $scope.name);
}
$rootScope.$on('nameChanged', function(event, data){
$scope.name = data;
})
}])