2013-03-13 51 views
54

嵌套的單擊事件我有一個HTML的結構是這樣的: 兩次與angularjs

<div ng-click="test()"> 
    <div id="myId" ng-click="test2()"></div> 
    <div></div> 
    ... 
</div> 

目前,當我在div點擊id爲myId那麼這兩個功能被觸發,但我想這只是test2功能得到觸發。我怎樣才能做到這一點?

+0

參見http://stackoverflow.com/questions/14544741/angularjs-directive-to-stoppropagation其中指令被定義爲停止繁殖。 – 2013-03-13 19:12:21

回答

105

所有你需要做的就是停止事件傳播/冒泡。

此代碼將幫助您:

<div ng-click="test()">ZZZZZ 
    <div id="myId" ng-click="test2();$event.stopPropagation()">XXXXX</div> 
    <div>YYYYYY</div> 
    ... 
</div> 

如果您testtest2功能將如下所示,你會在myId DIV點擊時只得到test2在控制檯。如果沒有$event.stopPropagation(),您將在控制檯輸出窗口中獲得test2,然後是test

$scope.test = function() { 
    console.info('test'); 
} 
$scope.test2 = function() { 
    console.info('test2'); 
} 
+1

對我來說就像一個魅力<3,謝謝 – 2015-04-09 06:11:05

+0

太棒了!這是最短的解決方案。謝謝 – 2015-12-03 17:12:37

+3

也適用於Angular2:'(click)=「test2(); $ event.stopPropagation()」'謝謝 – witters 2016-03-03 19:23:33

30

和湯姆的答案一樣,但有點不同。

 <div ng-click="test()"> 
      <div id="myId" ng-click="test2($event)">child</div> 
     </div> 

     $scope.test2 =function($event){ 
      $event.stopPropagation(); 
      console.log("from test2") 
     } 
     $scope.test =function(){ 
      console.log("from test") 
     } 
+0

+ +1這個答案保持停止傳播邏輯的視圖。 – sma 2014-05-07 15:40:25

+0

這是最好的答案,非常感謝 – Darktalker 2014-12-18 13:41:46

+6

我認爲這個邏輯**不屬於視圖,因爲否則控制器會假設內部函數將始終從該上下文中調用,並且它需要停止傳播每次。這使得內部功能的重用非常有限。如果視圖被重構,那麼控制器也必須重構。 – 2015-04-02 23:12:35

1

這是一個基於another question的指令,它支持ng-href鏈接。

指令

'use strict'; 


var myApp = angular.module('myApp', [ 
    'ngAnimate' 
    ]); 

/** 
* @ngdoc directive 
* @name myMobileApp.directive:stopEvent 
* @description Allow normal ng-href links in a list where each list element itselve has an ng-click attached. 
*/ 
angular.module('myApp') 
    .directive('stopEvent', function($location, $rootScope) { 
    return { 
     restrict: 'A', 
     link: function(scope, element) { 
     element.bind('click', function(event) { 

     // other ng-click handlers shouldn't be triggered 
     event.stopPropagation(event); 
     if(element && element[0] && element[0].href && element[0].pathname) { 
      // don't normaly open links as it would create a reload. 
      event.preventDefault(event); 
      $rootScope.$apply(function() { 
      $location.path(element[0].pathname); 
      }); 
     } 
     }); 
     } 
    }; 
    }) 


.controller('TestCtrl', ['$rootScope', '$scope', 'Profile', '$location', '$http', '$log', 
    function($rootScope, $scope, Profile, $location, $http, $log) { 
    $scope.profiles = [{'a':1,'b':2},{'a':3,'b':3}]; 

    $scope.goToURL = function(path, $event) { 
     $event.stopPropagation($event); 
     $location.path(path); 
    }; 

    } 
]); 
<div ng-repeat="x in profiles" 
    ng-click="goToURL('/profiles/' + x.a, $event)"> 

     <a stop-event ng-href="/profiles/{{x.b}}">{{x}}</a> 

    </div>