AngularJS - Controller routing to open link in new tab based on condition

Within my application, there are two distinct types of profiles available for organisations. When a user interacts with a profile name, the system must first determine if a premium profile exists for that organisation. If a premium profile is found, the user will be directed to that specific profile. However, in cases where no premium profile is present, the user will be redirected to the standard profile.

To accomplish this functionality, I have implemented an ng-click event that passes the ID and resource parameters (in this case, 'organisation') to a controller. Within the controller, certain conditions are evaluated before routing the user appropriately. This process works seamlessly when a user clicks on a profile as intended.

The issue arises when a user attempts to open the link in a new tab by right-clicking and selecting that option. In such scenarios, the new tab opens with the URL of the current page, indicating that the ng-click event and controller logic have not executed prior to the tab opening.

How can I modify my code to ensure that Angular processes the ng-click request before allowing the new tab to open? Essentially, how can I enable users to open these links in new tabs without simply displaying the current page?

HTML

<div ng-controller="ProfileRouter">
        <div ng-repeat="org in orgs | orderBy:'org.name'">
            <a href="" ng-click="profileCheck( '{{ org.id }}', 'organisation' )">{{ org.name }}</a>
        </div>
</div>

Inside the ProfileRouter controller:

$scope.profileCheck = function (id, resource) {

    $http({method: 'GET', url:'/IdCheck', params:{'id': id})
    .success(function(data) {

        var count = data.hits.found;
        if (count) {
            var hash = data.hits.hit[0].id;
        }

       if (resource == 'organisation') {
            theResource = 'universities';
            page = 'overview';
        }

        if (count == 1) {
            window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
        }
        if (count == 0) {
            window.location.href = "/" + resource + "/" + id;  
        }

     })
    .error(function(data) {
        $scope.data = data || "Can't get resource";
    });  
}

Answer №1

While this question may be old, I've come up with a solution that could benefit others.

To start off, I created a custom directive for handling right clicks:

module.directive('tabRightClick',['$parse', function($parse) {
    return function(scope, element, attrs) {
        var fn = $parse(attrs.tabRightClick);
        element.bind('contextmenu', function(event) {
            scope.$apply(function() {
    //            event.preventDefault();
                fn(scope, {$event:event});
            });
        });
    };
}]);

Next, I applied the directive as an attribute in the HTML file and used the same method called on ng-click:

<div ng-controller="ProfileRouter">
        <div ng-repeat="org in orgs | orderBy:'org.name'">
            <a href="{{locationPath}}" ng-click="profileCheck( '{{ org.id }}', 'organisation' )" tab-right-click= "profileCheck( '{{ org.id }}', 'organisation' )">{{ org.name }}</a>
        </div>
</div>

In this code snippet, locationPath is a variable bound to $scope, which needs to be set in the controller. Its value should be updated within the profileCheck function based on specific conditions.

$scope.profileCheck = function (id, resource) {

    $http({method: 'GET', url:'/IdCheck', params:{'id': id})
    .success(function(data) {

        var count = data.hits.found;
        if (count) {
            var hash = data.hits.hit[0].id;
        }

       if (resource == 'organisation') {
            theResource = 'universities';
            page = 'overview';
        }

        if (count == 1) {
            window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
            $scope.locationPath = "/" + theResource + "/profile/" + hash + "/" + page;
        }
        if (count == 0) {
            window.location.href = "/" + resource + "/" + id;  
            $scope.locationPath = "/" + resource + "/" + id;
        }

     })
    .error(function(data) {
        $scope.data = data || "Can't get resource";
    });  
}

I hope this explanation proves useful to someone out there.

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

The process of incorporating injected JavaScript into an existing function

It seems like a classic issue, but I haven't been able to find the solution. I have a form that connects to a MySQL (actually MariaDB) database table called contacts. As part of the jQuery.ready() function, a drop-down list is populated through AJAX ...

The blur event is failing to trigger in my custom input component

// The Custom Input component const Box = styled.div``; const InputBox = styled.div<{ width: string }>` display: flex; width: ${(props) => props.width}; height: 42px; justify-content: space-between; align-items: center; padding: 9px ...

Exploring the possibility of detecting page scrolling in Javascript by clicking on scroll bars

I have implemented a unique feature on my page that allows users to scroll up and down using custom buttons I created. This functionality is achieved by smoothly transitioning between anchor points on the page using jQuery's animate function. However ...

Transform a Javascript string variable into plain text within a pre-existing text document

Currently, I am storing user input from an HTML input as a JavaScript variable. The objective is to convert this data into plain text and save it in an existing text file. Essentially, each time the user provides input, it should be converted to plaintext ...

Error: Attempting to access the 'SearchBox' property of an undefined variable is not allowed

I have been working on a Google Maps code that displays both public and private schools with different markers for each category. However, when running the code, I encountered an error specifically on this line of code: var searchBox = new google.maps.pl ...

Updating the initialState in your application while employing the useState function with React Hooks

I'm currently facing an issue with updating the image value in the local state. Everything works fine initially, but once I return to the same page, the initialState seems to retain the previous value. To resolve this, I find myself having to assign t ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

Switch up a JSON string using JavaScript

I received a JS string through an AJAX API call containing data like this: {"Task":"Hours per Day","Slep":22,"Work":25,"Watch TV":15,"Commute":4,"Eat":7,"Bathroom":17} My goal ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

Guide on merging all Vue js functions into a single js file?

As a newcomer to vue.js, I am in the process of consolidating several functions into one js file. Here is an example: example.js: function containObject(obj, list) { for (let i = 0; i < list.length; i += 1) { if (list[i] === obj) { return ...

Is there a way to implement this code to filter every column in the grid?

I have been using this code in my grid view, but it only filters one column of the grid. Now I want to modify the code to filter multiple columns. I tried implementing a loop, but it seems like the code is not working correctly. Is there a way to adjust t ...

Acquiring mapping information through JSON data retrieval

Overview : Each levelNum has three corresponding dropdowns. For example, the dropdown for levelNum2 includes (Department-Unit-1, Department-Unit-2 & Department-Unit-3), levelNum3 includes (Division-Unit-1 & Division-Unit-2), and levelNum4 includes ...

What is the process for configuring a headless implementation of three.js on a node server, similar to the babylon.js-NulEngine setup?

My current project involves the development of a multiplayer three.js fps game, with client-side prediction in the browser. For the server-side implementation, I am utilizing Node.js Express.js and Socket.io for handling authoritative functions such as col ...

Performing a request following a POST operation within Postman

Currently, I am using a Post method on a URL which is expected to be written into a database. What I would like to do is create an "if" statement within the test tab in Postman to check the status of the response and then run a query to confirm that the ...

What could be causing my JSON product list to not load properly?

My list is not loading and I can't figure out why. I've included my json, jquery, and HTML below. The console isn't showing any errors, but the list is still blank. Any help would be greatly appreciated as I am new to working with json. Than ...

The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code: <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script> <script type="text/javascript"> var textWrapper = document.querySelector('.ml6 .letters'); textWrapper.in ...

Swap the content of one div with another div using client-side code only

Currently, I am in the process of developing my personal website. To enhance user experience, I have implemented a vertical navigation bar on the left side of the page. My goal is to replace the content of a specific div with content from other HTML files ...

Reloading a Nuxt.js page triggers the fetch function

I'm facing an issue with nuxt.js fetch(). Whenever I reload the page, it does not fetch the data again. It only fetches if I come from a router link. How can I force it to actually refetch the data from my API? export default { async fetch() { ...

Error encountered with AngularJS code when attempting to load content from another page using ajax

I'm currently tackling a challenge with AngularJs and php. Whenever I try to load content from another page, AngularJs seems to stop working. Let me provide you with a sample code snippet to illustrate my issue. main-page.php <div id="form-secti ...