Twee geneste klik-gebeurtenissen met Angularjs

Ik heb een HTML-structuur zoals deze:

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

Momenteel wanneer ik op de divmet de ID myIdklik>Dan worden beide functies geactiveerd, maar ik wil dat gewoon test2Functie Get Get Get Get Get Get Get GRAAGGERED . Hoe kan ik dat doen?


Antwoord 1, Autoriteit 100%

Alles wat u hoeft te doen, is om evenementenpropagatie / borrelen te stoppen.

Deze code helpt u:

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

Als uw testen test2Functies er als volgt uitzien, zou u alleen test2in uw console krijgen bij het klikken op myIddiv. Zonder $event.stopPropagation()U krijgt test2gevolgd door testin het CONSOLE-uitvoervenster.

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

Antwoord 2, Autoriteit 26%

hetzelfde als het antwoord van Tom, maar weinig anders.

       <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")
        }

Antwoord 3

Hier is een richtlijn op basis van een andere vraag die NG-HREF-koppelingen ondersteunt.

Richtlijn

'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>

Other episodes