instructions to selectively remove additional instructions

In my quest to develop a directive that can impact target elements in various ways, I have encountered three possible scenarios: 1. leaving the element unchanged, 2. removing all other directives before compilation to restrict user interactions (such as ng-click), or 3. completely eliminating the element.

While I have achieved success with all three options on specific elements, I faced an unexpected issue when applying option 2 to a button element. Rather than simply removing the ng-click directive, it resulted in a peculiar behavior where the event listener was duplicated. Despite there being no duplicate ng-click directives attached to the element upon inspection, clicking the button triggered the action twice.

Below is the current implementation of the directive along with the mock model I am currently utilizing.

return {
  restrict: 'A',
  priority: 1500,
  compile(elem, attr) {
    let action = () => { /**/ };

    const currentLocation = $location.path().split('/')[1];
    const permissionsLocation = appConfig[currentLocation];
    const fullPath = attr.permissions;
    if (_.has(permissionsLocation, fullPath)) {
      const permLevel = _.get(permissionsLocation, fullPath);
      if (permLevel === 'disable') {
        action = (scope, element) => {
          attr.$set('disabled');
          elem.css({
            cursor: 'not-allowed'
            // 'pointer-events': 'none'
          });
          elem
            .addClass('no-permissions')
            .removeAttr('ng-click')
            .removeAttr('ng-keyup')
            .removeAttr('ng-change')
            .removeAttr('ng-touchstart')
            .removeAttr('ng-touchend')
            .removeAttr('permissions');
          $compile(element)(scope);
        };
      } else if (permLevel === 'destroy') {
        action = (scope, element) => {
          element.remove();
        };
      }
    }
    return {
      pre(scope, element) {
        action(scope, element);
      }
    };
  }
};

The model:

appConfig.location1 = {
      thing1: {
        perm1: 'disable',
        perm2: 'destroy',
        perm3: 'destroy'
      },
      thing2: {
        perm4: 'disable'
      }
    };

This is how I would apply the directive:

<button ng-click="blah()" permissions="thing1.perm1"></button>

Answer №1

After trying various approaches, I stumbled upon a solution that involved switching from the pre method to the post method and immediately calling elem.off() after removing attributes. This successfully resolved the issue by eliminating all event listeners attached to the element I needed to deactivate. Oddly enough, either of these steps alone did not produce the desired result.

If anyone can shed light on why this workaround works or offer an alternative approach, I would greatly appreciate it and consider accepting that response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on efficiently inserting multiple records into a MySQL database using Node.js and also implementing a check to insert only when the record does not already exist

I need to add numerous records to a table while also checking for duplicates to ensure that only new records are inserted. I have successfully inserted a single record by checking for duplicates using the code below. connection.query(` INSERT INTO pla ...

Searching for an array of objects containing nested arrays in JavaScript

I've been struggling with this function for two days and still can't get it right. I need the function to only return objects that meet all filter criteria in the array. The issue is that it should only return objects that satisfy every filter. ...

Sending an object to a Vue 2 component and confirming its validity

I am working with a Vue component that has numerous props. <Field v-for="field in fields" :key="field.name" :name="field.name" :type="field.type" :label="field.label" :values="field.values" :value ...

What is the best way to incorporate gl-matrix into a ReactJS application?

Recently, I dabbled in using ReactJS and decided to experiment with this project that involves importing JS modules like this: import Particle from './Particle' I wanted to switch the project to use gl-matrix for practice with the framework, bu ...

How can I prevent a browser from allowing users to select an image tag?

I'm dealing with an issue on my webpage where I have an image that is inadvertently picking up mouse clicks, causing the browser to perform drag and drop actions or highlight the image when clicked. I really need to use the mousedown event for somethi ...

Discovering a specific grandparent using its ID and retrieving the values of its children based on a specific class can be achieved effortlessly with the power

I have a dynamic div <div class="illustartionWrap" id="illustartionWrapId"> <div class="illusList illusListTop" id="illusList_heading"> <span class="fileName">File Name</span> <span class="fileDesc" ...

Populate the table with JSON content using jQuery

I am attempting to populate a table with JSON data using jQuery, but the content within the div remains empty. I need assistance in identifying the error. The array list contains the data (I verified this using console.log(list)). Additionally, list[' ...

DaisyUI special design for managing inactive buttons

I have encountered an issue while creating a reddit Single Sign-On (SSO) button. The problem I'm facing is that the custom theme I designed for the Reddit button appears secondary-grey when it's disabled. Below is my theme configuration in the t ...

Problems with the configuration of the angular ui-grid settings object

I'm facing an issue with pushing data to my UI grid that I have configured in my Angular application. Here are the steps I followed: <div ng-controller="MainCtrl"> <div id="grid1" ui-grid="gridOptions" class="grid"></div> </di ...

Creating and inserting multiple objects into a table in Sails JS while bypassing any existing rows

Is there a way to insert an array of objects into a table while avoiding duplicate rows? I have a model defined as follows: //Test.js module.exports={ tableName:'test', connection: 'mysqlServer', attributes:{ id:{ type: ...

What is the process for incorporating attribute values when constructing XML with fast-xml-parser?

Latest fast-xml-parser update: version 4.3.6 Description I'm trying to incorporate an xml attribute (tokenized="true") in this format : <custom-tag tokenized="true">test test &gt; 14</custom-tag> Input Code var def ...

Can I construct an html table-esque layout employing fabric js?

https://i.stack.imgur.com/Zwkj3.jpg I'm in the process of developing a schema builder inspired by vertabelo. To achieve this, I've opted to utilize fabric.js for its interactive features. My main challenge lies in creating an HTML table-like str ...

What is the process of directing to another HTML page within the same Express controller script?

I am looking to switch the initial page (login page) to a second page (admin dashboard) from within the same controller in Express after a specific action has been taken. Here is the relevant code snippet from my controller file nimda.js: function handle ...

Is there a way to enlarge the font size for a complete tag?

I'm having trouble with a project. One of the tasks is to use jQuery or JavaScript to increase the font size of a paragraph. The console statements are incrementing by +1 with every mouse click (the first click adds 1, the second adds 2, and so on). ...

Error: An undefined property 'spirit' is being accessed causing a TypeError. To fix this issue, simply refresh the page to successfully read the property

const QueueItem = (props) => { let spirit = props.drink.spirit ? ( <div> {props.drink.spiritquantity} | {props.drink.spirit} </div> ) : ( <div> No Spirit </div> ); let liqueur = props.drink.liqueur ? ( ...

Adjusting the transparency level of the map outside a circular zone in the Google Maps JavaScript API v

Currently, I am adding a circle to my map: var optionsCircle = { center: latlang, map: map, radius: 1000, fillOpacity: 0.1, strokeWeight: 0 }; this.circle = new google.maps.Circle(optionsCircle); Instea ...

Which phase is affected by the stopPropagation method?

Quirksmode explains that modern browsers have a capturing phase as well as a bubbling phase, which you can read more about here. If I decide to implement stopPropagation in my event handler with a Boolean argument specifying the phase, how will it behave? ...

I am facing issues with running my project due to a gyp error. Can anyone provide guidance on resolving this problem?

Every time I execute my code, I encounter the same persistent error. Despite attempting to resolve it by uninstalling and reinstalling Node and npm, the issue persists. Furthermore, the lack of "node_modules" exacerbates the problem. How can I rectify this ...

When rendering a PNG image with an alpha channel, three.js has been reported to leak pixels from the videocard

Struggling to come up with a suitable title for my question here.. I'm encountering an issue when loading PNG files from an external URL, specifically with one PNG that has a non-power-of-two alpha channel created in Gimp. When I load and use this PNG ...

Error in AngularJs: Unable to assign value to 'showGreeting' property because it is null

Currently, I am utilizing yeoman angularjs-fullstack for project generation. Now, my task is to customize it according to my preferences. I have limited experience with AngularJS and TypeScript, so any feedback would be greatly appreciated, not just the so ...