您的位置:首页 > Web前端 > AngularJS

Angular ngClick 阻止冒泡和默认行为

2016-05-09 14:13 696 查看

Angular ngClick 阻止冒泡和默认行为

困扰了几天的麻烦,如果你认真查看过Angular官方的API文档,这其实是一个很简单的问题。在Angular中已经对一些ng事件如ngClick,ngBlur,ngCopy,ngCut,ngDblclick…中加入了一个变量叫做$event.如ngClick在官方文档是这么描述的:
Expression to evaluate upon click. (Event object is available as $event)
在查看Angular代码ngEventDirs.js:
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return {
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
};
}];
}
);
在上边代码我们可以得到两个信息:[/code]Angular支持的event: click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut pasteAngular在执行事件函数时候传入了一个名叫$event的常量,该常量即代表当前event对象,如果你在Angular之前引入了jQuery那么这就是jQuery的event.所以我们可以利用event的stopPropagation来阻止事件的冒泡:如下代码:jsbinhtml 代码:
<!DOCTYPE html>
<html id="ng-app" ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="demo as d">
<div ng-click="d.click('parent',$event)">
given some text for click
<hr>
<input type="checkbox" ng-model="d.stopPropagation" />Stop Propagation ?
<hr>
<button type="button" ng-click="d.click('button',$event)">button</button>

</div>
</body>
</html>
js 代码:
angular.module("app",[])
.controller("demo",[function(){
var vm = this;

vm.click = function(name,$event){
console.log(name +" -----called");
if(vm.stopPropagation){
$event.stopPropagation();
}
};

return vm;
}]);

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: