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](https://github.com/angular/angular.js/blob/a68624444afcb9e3796b1a751cf3817cafd20240/src/ng/directive/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});
                    });
                  });
                };
              }
            };
          }];
        }
      );


在上邊代碼我們可以得到兩個信息:

1. Angular支持的event: click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste

2. Angular在執行事件函數時候傳入了一個名叫$event的常量,該常量即代表當前event對象,如果你在Angular之前引入了jQuery那麼這就是jQuery的event.

所以我們可以利用event的stopPropagation來阻止事件的冒泡:如下代碼:[jsbin](http://jsbin.com/delow/3/watch?html,js,output)

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](http://jsbin.com/delow/3/watch?html,js,output)查看效果。

首先打開你的控制檯,然在沒選中Stop Propagation的情況下點擊button你將會看見兩條log記錄,相反選中後則只會出現button的log信息。

希望大家已經明白了,不要再問這類問題了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章