Click on the child element

3

I made a directive that I insert it in the div father to restrict some things (such restrictions that I do not put in the example), but I also want to listen when click in the second element only in the second element, how can I listen when click ?

Note: I just want to insert the

directive into the parent 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>
    
asked by hubman 21.09.2017 в 03:48
source

2 answers

3

It's as easy as checking who is receiving the event:

angular
  .module('MyApp', [])
  .directive(
    'clickMe',
    function() {
      return {
        link: function(scope, element) {
          
          element.on('click', function(evento) {
            if (evento.target.id=='one') {
              console.log('Click on click 2');
            } else {
              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>
    
answered by 21.09.2017 в 11:42
1

I've found a way to do what you want, but it only works with jQuery .

If you notice, I added the id #one of the div

element.on('click', '#one', function () 

angular
  .module('MyApp', [])
  .directive(
    'clickMe',
    function() {
      return {
        link: function(scope, element) {
           element.on('click', '#one', function () {
            console.log('click');
          });
        },
      };
    }
  );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
    
answered by 21.09.2017 в 09:37