Reputation: 149
I made a directive that I insert it in the div parent to restrict some things (such restrictions that I do not put in the example), but I also want to listen when you click on the second element only in the second element, how can I listen when you click?
note: I just want to insert in div father the directive
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>
Upvotes: 0
Views: 47
Reputation: 3393
This would be an alternative way to add the event listener to only the child 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');
});
},
};
}
);
Upvotes: 2
Reputation: 222720
Change your directive as follows,
angular
.module('MyApp', [])
.directive(
'clickMe',
function() {
return {
link: function(scope, element) {
element.on('click', function(event) {
if (event.target.id == "one") {
console.log('click');
}
});
},
};
}
);
DEMO
angular
.module('DemoApp', [])
.directive(
'clickMe',
function() {
return {
link: function(scope, element) {
element.on('click', function(event) {
if (event.target.id == "one") {
console.log('click');
}
});
},
};
}
);
<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>
Upvotes: 2