web-dev-qa-db-ja.com

angularjsを使用した2つのネストされたクリックイベント

次のようなHTML構造があります。

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

現在、ID divを持つmyIdをクリックすると、両方の関数がトリガーされますが、ただtest2関数がトリガーされます。どうやってやるの?

58
Safari

必要なのは、イベントの伝播/バブリングを停止することだけです。

このコードは次のことに役立ちます。

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

testおよび_test2_関数が次のように見える場合、myId DIVをクリックすると、コンソールに_test2_のみが表示されます。 $event.stopPropagation()がなければ、コンソール出力ウィンドウで_test2_に続いてtestが表示されます。

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

トムの答えと同じですが、少し違います。

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

以下は、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>
1
s.Daniel