本文實例講述了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}); }); }); }; } }; }]; });
在上邊代碼我們可以得到兩個信息:
①. Angular支持的event: click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste
②. Angular在執行事件函數時候傳入了一個名叫$event的常量,該常量即代表當前event對象,如果你在Angular之前引入了jQuery那么這就是jQuery的event.
所以我們可以利用event的stopPropagation來阻止事件的冒泡:如下代碼:jsbin
html 代碼:
<!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;}]);
可以在jsbin查看效果。
首先打開你的控制臺,然在沒選中Stop Propagation的情況下點擊button你將會看見兩條log記錄,相反選中后則只會出現button的log信息。
希望本文所述對大家AngularJS程序設計有所幫助。
|
新聞熱點
疑難解答