Disable ngClick

Angular’s ngClicks can be attached to anything. This makes it easy to add interactivity to elements on the DOM. Your program might require that these click callbacks be disabled at certain points, such as during form processing. ngClick doesn’t have a toggle built in. Let’s build one that might help.

In our app we’re going to track the state of the UI via various events that get passed in scope. We slap our directive as an attribute on an element and it will respond by disabling or enabling on certain events. Here’s the directive:

The directive allows for listening on multiple events. This is useful if your button should be disabled/enabled via multiple events. Just separate your event list with commas. If you don’t want to specify any events, the directive uses two default events, ‘click:disable’ and ‘click:enable’.

The directive sets the disabled attribute, commonly used in form fields. It also sets the is-disabled class so your app can style this state consistently in the UI.

Lastly, the directive also sets a scope.disabledToggled variable on the scope of the element. This will be useful for elements which are not form elements and which do not prevent clicking just because their disabled attribute is set to disabled. Instead, we’ll use this value to short-circuit the ng-click event itself.