Angular Event事件
發送事件方法:
$scope.$emit('name', 'args');
(向子$scope傳遞事件)
或者是
$scope.$broadcast('name', 'args');
(向父$scope傳遞事件)
接受事件的方法:
$scope.$on('name', 'args');
區別:
<div ng-controller="ParentCtrl">
<div ng-controller="SelfCtrl">
<a class="btn" ng-click="click()">click me</a>
<div ng-controller="ChildCtrl"></div>
</div>
<div ng-controller="BroCtrl"></div>
</div>
這裏我們有四個controller, 層級關係如下:
ParentCtrl
-> SelfCtrl (*)
-> ChildCtrl
-> BroCtrl
所有的事件都是由 SelfCtrl 發出去的.
broadcast
事件發送的方法:
$scope.$broadcast
值得注意的是發送的主語是 $scope, 因爲所有的事件其實都是作用在scope上的。
broadcast 是從發送者向他的子scope發送時間的一個方法。 這裏就是SelfCtrl發送, SelfCtrl 和 ChildCtrl 會接受到, 而ParentCtrl是不會收到的
事件的接受只有一個方法
$scope.$on
eg.
angular.module('TestApp', ['ng'])
.controller('ParentCtrl', function($scope) {
$scope.$on('to-child', function(e, d) {
console.log('關我毛事');
});
})
.controller('SelfCtrl', function($scope) {
$scope.click = function () {
$scope.$broadcast('to-child', 'haha');
$scope.$emit('to-parent', 'hehe');
}
})
.controller('ChildCtrl', function($scope){
$scope.$on('to-child', function(e, d) {
console.log('I\' the child, I got it', d);
});
})
.controller('BroCtrl', function($scope){
$scope.$on('to-child', function(e, d) {
console.log('關我毛事');
});
})
;
點擊clickme後, 在console裏是看不到“關我毛事“的, 原因嘛就是 “管他毛事啊”
Emit
emit 類似
angular.module('TestApp', ['ng'])
.controller('ParentCtrl', function($scope) {
$scope.$on('to-parent', function(e, d) {
console.log('we are the parent, I got it', d);
});
})
.controller('SelfCtrl', function($scope) {
$scope.click = function () {
$scope.$broadcast('to-child', 'haha');
$scope.$emit('to-parent', 'hehe');
}
})
.controller('ChildCtrl', function($scope){
$scope.$on('to-parent', function(e, d) {
console.log('關我毛事');
});
})
.controller('BroCtrl', function($scope){
$scope.$on('to-parent', function(e, d) {
console.log('關我毛事');
});
})
;
Notes
上面的例子可以看到, 事件和事件發生者的兄弟是沒有關係的, 怎樣都收不到。
上面就是簡單的事件介紹, 至於怎樣組織事件傳播、怎樣拿到事件參數, 下回再說 ;)