Reputation: 4440
I am still new to angular, and trying to get the hang of directives. I have a special use case that is a bit hard to explain, but I've made a very basic demo of what it needs to do.
Basically, there is a parent object that will contain any number of layers and markup. For specific reasons, I need to be able to ignore any kind of mouse clicks that occur within this layer unless the click is on a link.
Can this be re-written to be a simple attribute directive?
Here is a working jsBin to show how I am currently achieving my result. I want to make it simpler by turning it into a custom directive.
When I say clicks need to be ignored, I mean that they very explicitly need to be overridden to be ignored. This is not a case of needing to just attach ng-click
to the <a>
tag. The reason is because the content will vanish when a mouse click is triggered. I want the user to be able to interact (highlight, select, copy, etc) with the content without it vanishing on them unintentionally.
I have this working like I want, but I want to go a step further. Right now, I have to attach this as an ng-click
, like this;
<div ng-click="checkIfLink($event)">
<div> // ... some html content ... // </div>
<div> // ... some html content ... // </div>
<div> <a href="#link">Hyperlink</a> </div>
</div>
That works, but I'd like to try more with directives and see if I can make this more declarative. I would ideally like to reduce it to something as simple as ...
<div ignore-clicks>
<div> // ... some html content ... // </div>
<div> // ... some html content ... // </div>
<div> <a href="#link">Hyperlink</a> </div>
</div>
This is obviously a really trivial example, I have a jsBin drafted up to demonstrate how the code kind of works now. In my example, if you click on a part of the box that should not let mouse clicks pass through, it will just change the background color of the box. If you click on the link, it will function as normal.
(function(){
var app = angular.module("app", []);
app.controller("DemoController", function($scope){
$scope.checkIfLink = function($event){
if($event.target.tagName !== 'A'){
$event.preventDefault();
$event.stopPropagation();
// change the background color just as part of the demo
$event.target.style.background = $scope.getRandomColor();
}
}
$scope.getRandomColor = function(){
var hex = Math.floor(Math.random() * 0xFFFFFF);
return '#' + ("000000" + hex.toString(16)).substr(-6);
}
});
})();
<body ng-app="app">
<div ng-controller="DemoController">
<div id="square" ng-click="checkIfLink($event)">
<a href="#test">Test</a>
</div>
</div>
</body>
Upvotes: 0
Views: 102
Reputation: 3395
You can use link
function to attach event listener to the element.
app.directive('ignoreClicks', function(){
return {
link: function(scope, element, attrs) {
element.on('click', function(evt) {
if(evt.target.tagName !== 'A'){
evt.preventDefault();
evt.stopPropagation();
}
else {
console.log('click');
}
});
}
};
});
Upvotes: 1