问题
LIVE DEMO
Consider the following myButton
directive:
angular.module("Demo", []).directive("myButton", function() {
return {
restrict : "E",
replace: true,
scope: {
disabled: "="
},
transclude: true,
template: "<div class='my-button' ng-class='{ \"my-button-disabled\": disabled }' ng-transclude></div>",
};
});
which can be used like this:
<my-button disabled="buttonIsDisabled"
ng-click="showSomething = !showSomething">
Toggle Something
</my-button>
How could I stop ng-click
from executing when buttonIsDisabled
is true
?
PLAYGROUND HERE
回答1:
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.
回答2:
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.
回答3:
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
回答4:
<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?
来源:https://stackoverflow.com/questions/23366134/how-to-stop-ng-click-from-a-custom-directive-in-angularjs