Associate the right-click action with Angular Material

I'm currently working with Angular Material.

My goal is to develop a directive that allows me to trigger a right-click event on an element.

This is what I have attempted so far:

JavaScript:

app.directive('rightClick', ["$parse", function($parse) {
    return {
        restrict: 'A',
        link: function($scope, element, attrs) {
            var fn = $parse(attrs.rightClick);
            element.bind('contextmenu', function(event) {
                $scope.$apply(function() {
                    event.preventDefault();
                    fn($scope, {$event:event});
                });
            });
        }
    }
}])

HTML:

<md-menu md-position-mode="target-right bottom">
<md-button right-click="$mdOpenMenu($event)" aria-label="Open some menu">
    Right click
</md-button>
<md-menu-content>
    <md-menu-item>
        <md-button ng-click="doSomething()" aria-label="Do something">
            Action
        </md-button>
    </md-menu-item>
</md-menu-content>

The issue I am facing is that the menu does not appear in the correct position.

Instead of showing up where I right-clicked, it appears at the top left of the page.

How can I create a directive that mimics the behavior of ng-click but for right-click events and works seamlessly with Angular Material?

UPDATE:

Thank you for your response, Catmandu.

I attempted to implement a similar directive, but unfortunately, it did not resolve the problem.

Here is a visual representation of my issue:

Result using custom "ng-right-click" directive which triggers contextmenu:

Result using AngularJS "ng-click" directive:

With my custom directive, the menu still fails to display in the desired top/left position.

Answer №1

To add a specific action for right-click using the contextmenu event, you can create a directive like this:

app.directive('ngRightClick', function($parse) {
    return function(scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function(event) {
            scope.$apply(function() {
                event.preventDefault();
                fn(scope, {$event:event});
            });
        });
    };
});

It's recommended to use direct return function and avoid restrict in this case.

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

Maintaining consistent height using JavaScript

Dealing with equal height using just CSS can be a hassle, especially when you want to support older browsers like IE9. That's why I've decided to use JavaScript instead. If a user disables JavaScript, having unequal heights is the least of my con ...

Initial part before entering the line of input

Is there a way to add a prefix to input blocks similar to how Python does it? E:\Users\foobar\Downloads\KahootTest1>py Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", ...

A different approach to joining strings

Is there a different method to combine a '#' symbol like in the code snippet below? radioButtonID = '#' + radioButtonID; ...

No data returned from Ajax GET request

Utilizing Ajax with JavaScript, I am processing data on a PHP page using the GET method. Is it possible to send data from the PHP page when the GET query is empty? My goal is to have a live search feature that filters results based on user input. When a us ...

transform a nested JavaScript object into a one-dimensional array

There is a JavaScript object in the following format: { "draw": "", "columns": [ { "data": "userid", "name": "", "searchable": true, "search": { "value": "", "regex": false } } ] } I want to tra ...

Is it feasible to have unique popups for individual textbox edits?

I am experiencing a problem with a popup in Asp.net while using AJAX modalpopup extender. I am wondering if it is feasible to display one type of popup when the user modifies certain textboxes, and another type of popup for the remaining textboxes. I beli ...

Retrieve data from AJAX once the cycle is complete

Currently, I am attempting to calculate the sum of results from an external API by making a single request for each keyword I possess. The code is functioning properly; however, the function returns the value before all the ajax requests are completed. Eve ...

The property 'get' cannot be accessed because the axios module of vue__WEBPACK_IMPORTED_MODULE_0__ is undefined

Having some trouble with Vue and Axios - encountering the following error message: [Vue warn]: Error in created hook: "TypeError: can't access property "get", vue__WEBPACK_IMPORTED_MODULE_0__.default.axios is undefined" Here's the code snippet: ...

Jquery button click event is malfunctioning after the inclusion of jquery keyboard plugin

When I try to gather user input from a textbox using jQuery keyboard.js, the functionality works perfectly fine if I exclude the virtual keyboard code. For more information on keyboard.js, you can visit: https://github.com/Mottie/Keyboard/wiki Below is t ...

Run JavaScript code before finalizing the "submit" action within a Ruby on Rails application

Having trouble with utilizing old JS scripts found on Stack Overflow. <div class="form-actions"> <%= f.button :submit, class:"btn btn-success create-campaign" %> </div> The submit button is causing an issue for me. <div clas ...

Show/Hide All Actions in a Vue.js table using Bootstrap styling

In my Vue.js project, I created a bootstrap table to display data loaded from local JSON files. One of the features I added is the ability to Show/Hide details of specific rows, which shows a full message for that row. Now, I'm looking for a way to im ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

Error: The variable fullName has not been declared

To start off, I need to develop a registration form that includes fields for full name, email, password, mobile number, and date of birth. Once the email validation is successfully completed and the submit button is clicked, the user should be redirected t ...

New and improved method for showcasing the switching of two PHP variables using jQuery Ajax

Obtaining two random values from a table in the same row can be achieved using PHP and MySQL. For example: <?php $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection); $row = mysql_fetch_array($result); echo $ro ...

Implement pagination for API calls within a React Component

I am trying to implement pagination for the results of an API call. The following code snippet shows how I am making the API call using Axios: apiCall() { const API = `http://www.omdbapi.com/`; axios.get(API, { params: { apikey: proces ...

Angular's ng-repeat allows you to iterate over a collection and

I have 4 different product categories that I want to display in 3 separate sections using AngularJS. Is there a way to repeat ng-repeat based on the product category? Take a look at my plnkr: http://plnkr.co/edit/XdB2tv03RvYLrUsXFRbw?p=preview var produc ...

Encountering challenges with the migration of JHipster from version 2.2x to 3.4 due to changes in the structure

Last winter, I embarked on a project with JHipster and recently updated it to the latest version (3.4). Despite following the documentation's guidelines, I noticed that the JS controllers generated by JHipster differ from the ones previously created. ...

Monitor the closure of a programmatically opened tab by the user

Currently, I am in the process of developing a web application using Angular 11 that interacts with the msgraph API to facilitate file uploads to either onedrive or sharepoint, and subsequently opens the uploaded file in the Office online editor. Although ...

Is it possible to retrieve the IMEI number of a mobile phone using expo?

Currently working on developing a mobile app with React Native using Expo. I need to figure out a way to access the client's mobile IMEI number and display it in the front end of the app. Unsure of how to accomplish this task. Is there a method to do ...

Oops! Before proceeding, make sure to call TestBed.initTestEnvironment() first

Currently, I am experimenting with testing a service in Angular. Below is the code snippet I am working on: describe('AddressService', () => { let service: AddressService; let injector: TestBed; let httpTestingController: HttpTesting ...