概述
Angular JS对各种事件进行了对应指令的封装,使其能够更好的配合Angular JS使用。具有ng指令的事件:
事件 | 指令 | 说明 |
---|---|---|
click | ng-click | 鼠标左键单击 |
dblclick | ng-dblclick | 鼠标左键双击 |
mousedown | ng-mousedown | 鼠标点下 |
mouseup | ng-mouseup | 鼠标弹起 |
mouseover | ng-mouseover | 鼠标位于上方 |
mouseout | ng-mouseout | 鼠标移出 |
mousemove | ng-mousemove | 鼠标移动 |
mouseenter | ng-mouseenter | 鼠标进入 |
mouseleave | ng-mouseleave | 鼠标进入 |
keydown | ng-keydown | 键盘按下 |
keyup | ng-keyup | 键盘弹起 |
keypress | ng-keypress | 键盘按住 |
submit | ng-submit | 提交 |
focus | ng-focus | 获得焦点 |
blur | ng-blur | 失去焦点 |
copy | ng-copy | 拷贝 |
cut | ng-cut | 剪切 |
paste | ng-paste | 粘贴 |
实现细节
所有的消息的ng指令都是采用统一的处理模式,就是监听对应的消息,然后执行绑定的数据。核心代码为:
element.on(eventName, function(event) {
var callback = function() {
fn(scope, {$event:event});
};
if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
样例代码
<!DOCTYPE html>
<html lang="en" ng-app="app">
<!--<html>-->
<head>
<title>Test</title>
</head>
<body>
<div>
<button ng-click="clickCount = clickCount + 1" ng-init="clickCount=0">
click {{clickCount}}
</button>
<button ng-dblclick="dbclickCount = dbclickCount + 1" ng-init="dbclickCount=0">
Double click {{dbclickCount}}
</button>
<button ng-mousedown="mdclickCount = mdclickCount + 1" ng-init="mdclickCount=0">
Mouse down {{mdclickCount}}
</button>
<button ng-mouseup="muclickCount = muclickCount + 1" ng-init="muclickCount=0">
Mouse up {{muclickCount}}
</button>
<button ng-mouseover="moclickCount = moclickCount + 1" ng-init="moclickCount=0">
Mouse over {{moclickCount}}
</button>
</div>
<script src="./node_modules/angular/angular.js" type="text/javascript"></script>
<script>
angular.module('app', []);
</script>
</body>
</html>
网友评论