单击子元素

时间:2017-09-21 01:58:43

标签: angularjs

我做了一个指令,我将它插入div父级以限制一些事情(这些限制我没有放在示例中),但我也想听,当你只在第二个元素中点击第二个元素,当你点击时我该怎么听?

注意:我只想在div父中插入指令

angular
  .module('MyApp', [])
  .directive(
    'clickMe',
    function() {
      return {
        link: function(scope, element) {
          element.on('click', function() {
            console.log('click');
          });
        },
      };
    }
  );
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div click-me>
    clickeame
    <div id="one">
      click 2
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

更改指令,如下所示,

angular
  .module('DemoApp', [])
  .directive(
    'clickMe',
    function() {
      return {
        link: function(scope, element) {
          element.on('click', function(event) {
            if (event.target.id == "one") {
              console.log('click');
            }
          });
        },
      };
    }
  );

<强>样本

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="DemoApp">
  <div click-me>
    clickeame
    <div id="one">
      click 2
    </div>
  </div>
</div>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:2)

这是将事件侦听器仅添加到子级的替代方法 https://codepen.io/anon/pen/eGzBQm

angular
  .module('MyApp', [])
  .directive(
    'clickMe',
    function() {
      return {
        link: function(scope, element) {
          element.find("div").on('click', function(event) {
              console.log('click');

          });
        },
      };
    }
  );