(1)angular js支持的事件
- ng-click
- ng-dbl-click
- ng-mousedown
- ng-mouseenter
- ng-mouseleave
- ng-mousemove
- ng-keydown
- ng-keyup
- ng-keypress
- ng-change
點擊按鈕,實現“測試”的顯示與隱藏
<!DOCTYPE html>
<html ng-app="testEvent">
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="myctrl">
<span ng-hide="isHide">測試</span>
<button ng-click="toggle()">隱藏/顯示</button>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
var app = angular.module(
"testEvent",
[]
);
app.controller("myctrl",function($scope){
$scope.isHide = false;
$scope.toggle = function(){
$scope.isHide = !$scope.isHide;
}
});
</script>
</body>
</html>
(3)自定義事件傳播
1.前提
必須有controller嵌套,否則無法接收事件<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的層級關係如下:所有的事件都是從SelfCtrl發出
2.$broadcast
事件發送的方法:
$scope.$broadcast
事件的接收方法:
$scope.$on
broadcast是從發送者向他的子scope發送事件的一個方法,所以父scope不會收到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');
}
})
.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('關我毛事');
});
})
;
3.$emit
事件發送的方法:
$scope.$broadcast
只有父scope能夠收到
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.$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('關我毛事');
});
})
;
4.說明
不管是$broadcast還是$emit,兄弟controller永遠都不會收到事件