Enable/Disable Anchor Tags using AngularJS

后端 未结 11 1535
一整个雨季
一整个雨季 2020-12-01 05:45

How do I enable/disable anchor tags using the directive approach?

Example:

  1. while clicking on edit link, create & delete needs to be disabled or g
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 06:25

    You can create a custom directive that is somehow similar to ng-disabled and disable a specific set of elements by:

    1. watching the property changes of the custom directive, e.g. my-disabled.
    2. clone the current element without the added event handlers.
    3. add css properties to the cloned element and other attributes or event handlers that will provide the disabled state of an element.
    4. when changes are detected on the watched property, replace the current element with the cloned element.

    HTML

       CREATE
    EDIT
    DELETE
    RESET

    JAVASCRIPT

    directive('myDisabled', function() {
      return {
    
        link: function(scope, elem, attr) {
          var color = elem.css('color'),
              textDecoration = elem.css('text-decoration'),
              cursor = elem.css('cursor'),
              // double negation for non-boolean attributes e.g. undefined
              currentValue = !!scope.$eval(attr.myDisabled),
    
              current = elem[0],
              next = elem[0].cloneNode(true);
    
          var nextElem = angular.element(next);
    
          nextElem.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
          });
    
          nextElem.css('color', 'gray');
          nextElem.css('text-decoration', 'line-through');
          nextElem.css('cursor', 'not-allowed');
          nextElem.attr('tabindex', -1);
    
          scope.$watch(attr.myDisabled, function(value) {
            // double negation for non-boolean attributes e.g. undefined
            value = !!value;
    
            if(currentValue != value) {
              currentValue = value;
              current.parentNode.replaceChild(next, current);
              var temp = current;
              current = next;
              next = temp;
            }
    
          })
        }
      }
    });
    

提交回复
热议问题