AngularJS可以为 元素添加 指令 ,让浏览器编译的时候能够读取该指令
下面是一个简单的例子:
<script>
<span style="white-space:pre"> </span> angular.module('eventTest', []). //为evenTest绑定directive
<span style="white-space:pre"> </span>directive('click',['$window','$document',function($window,$document) { //为directive 注入 $window,$document,
<span style="white-space:pre"> </span>return function(scope, element, attr) { //范围,元素(相当于$("#id")), attr:DOM属性
<span style="white-space:pre"> </span> element.bind('click', function(event) { //绑定动作
<span style="white-space:pre"> </span>checkButtonDOM(attr);
<span style="white-space:pre"> </span> });
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>function checkButtonDOM(attr){
<span style="white-space:pre"> </span>if(attr.type=="button"){
<span style="white-space:pre"> </span>$window.alert(attr.id);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}]);
<span style="white-space:pre"> </span>
</script>
</head>
<body ng-app="eventTest">
<button click type="button" id="butoonId">Click me</button>
</body>
还有一个网上的例子:用于拖拽
<script>
angular.module('drag', []).
directive('draggable', function($document) {
var startX=0, startY=0, x = 0, y = 0;
return function(scope, element, attr) {
element.css({ //绑定元素的样式
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});
element.bind('mousedown', function(event) { //绑定动作
startX = event.screenX - x;
startY = event.screenY - y;
$document.bind('mousemove', mousemove);
$document.bind('mouseup', mouseup);
});
function mousemove(event) {
y = event.screenY - startY;
x = event.screenX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
});
</script>
</head>
<body ng-app="drag">
<span draggable>Drag ME</span>
</body>
原文来自 http://angularjs.cn/A00p