How do I enable/disable anchor tags using the directive approach?
Example:
JAVASCRIPT:
angular.module('ngApp', []).controller('ngCtrl',['$scope', function($scope){ $scope.create = function(){ console.log("inside create"); }; $scope.edit = function(){ console.log("inside edit"); }; $scope.delete = function(){ console.log("inside delete"); }; }]).directive('a', function() { return { restrict: 'E', link: function(scope, elem, attrs) { if(attrs.ngClick || attrs.href === '' || attrs.href === '#'){ elem.on('click', function(e){ e.preventDefault(); if(attrs.ngClick){ scope.$eval(attrs.ngClick); } }); } } }; });
LINK to CODE
We can conditionally enable or disable anchor tags using ng-Show or ng-Hide directives.
To disable a HTML anchor element with CSS, we can apply the pointer-events: none style. pointer-events: none will disable all click events on the anchor element. This is a great option when you only have access to class or style attributes. It can even be used to disable all the HTML links on a page.
Disable a link #remove the href attribute so that it can no longer receive the focus. add a role="link" so that it is always considered a link by screen readers. add an attribute aria-disabled="true" so that it is indicated as being disabled.
Update: Disabling the href works better in the link function return. Code below has been updated.
aDisabled
naturally executes before ngClick
because directives are sorted in alphabetical order. When aDisabled
is renamed to tagDisabled
, the directive does not work.
To "disable" the "a" tag, I'd want the following things:
href
links not to be followed when clickedngClick
events not to fire when clickeddisabled
classThis directive does this by mimicking the ngDisabled directive. Based on the value of a-disabled
directive, all of the above features are toggled.
myApp.directive('aDisabled', function() { return { compile: function(tElement, tAttrs, transclude) { //Disable ngClick tAttrs["ngClick"] = "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")"; //return a link function return function (scope, iElement, iAttrs) { //Toggle "disabled" to class when aDisabled becomes true scope.$watch(iAttrs["aDisabled"], function(newValue) { if (newValue !== undefined) { iElement.toggleClass("disabled", newValue); } }); //Disable href on click iElement.on("click", function(e) { if (scope.$eval(iAttrs["aDisabled"])) { e.preventDefault(); } }); }; } }; });
Here is a css style that might indicate a disabled tag:
a.disabled { color: #AAAAAA; cursor: default; pointer-events: none; text-decoration: none; }
And here is the code in action, with your example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With