LIVE DEMO
Consider the following myButton
directive:
angular.module(\"Demo\", []).directive(\"myButton\", function() {
return {
re
Why not use the actual button for your button. You could change your directive to:
angular.module("Demo", []).directive("myButton", function() {
return {
restrict : "E",
replace: true,
scope: {
disabled: "="
},
transclude: true,
template: "<button class='my-button' ng-class='{ \"my-button-disabled\": disabled }' ng-disabled='disabled' type='button' ng-transclude></button>"
};
});
Then style it to look like your div. See the Short Example I've made.
<my-button disabled="buttonIsDisabled"
ng-click="showSomething = buttonIsDisabled ? showSomething : !showSomething">
or
<my-button disabled="buttonIsDisabled"
ng-click="showSomething = buttonIsDisabled ? function(){} : !showSomething">
Is this too simple?
You could use capture (addEventListener's optional third parameter) and stop the propagation of the event (using stopPropagation).
"Capture" allows you to catch the event before it reaches the "bubble" phase (when the triggering of "normal" event-listeners happens) and "stopPropagation" will...stop the propagation of the event (so it never reaches the bubbling phase).
element[0].addEventListener('click', function (evt) {
if (scope.disabled) {
console.log('Stopped ng-click here');
evt.preventDefault();
evt.stopPropagation();
}
}, true);
See, also, this short demo.
Try this in your link function:
link: function(scope, element, attrs) {
var clickHandlers = $._data(element[0]).events.click;
clickHandlers.reverse(); //reverse the click event handlers list
element.on('click', function(event) {
if (scope.disabled) {
event.stopImmediatePropagation(); //use stopImmediatePropagation() instead of stopPropagation()
}
});
clickHandlers.reverse(); //reverse the list again to make our function at the head of the list
}
DEMO
This solution uses jQuery to deal with cross browser problems. The idea here is to attach our event handler at the head of the click handlers list and use stopImmediatePropagation() to stop current handlers of the same event and bubbling event.
Also take a look at this: jquery: stopPropagation vs stopImmediatePropagation