AngularJS - Launching a new tab with a specified URL

After logging into my application, I am attempting to automatically open the admin page in a new tab instead of reloading the public page. However, my current code isn't working as expected:

var url = $state.href('/admin/overview');
$window.open(url, '_blank');

If you have any suggestions or tips on how to achieve this, please let me know. Thank you!

Answer №1

Check out this JSFiddle for a solution that involves injecting $window before using it:

Angular JS code:

angular.module('myApp', [])
    .controller('example', ['$scope', '$window', function ($scope, $window) {
        $scope.openGoogle = function () {
            $window.open('https://www.google.com', '_blank');
        };
    }]);

HTML code:

<div ng-app="myApp" ng-controller="example">
    <a href="#" ng-click="openGoogle()">Click here to visit Google</a>
</div>

Answer №2

Check out this functional JSFiddle link

The HTML code is as follows:

<div ng-controller="MyCtrl">
<a ng-href="{{url}}" target="_blank">Go to jsfiddle</a>
</div>

Here's the corresponding JS code:

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
    $scope.url ='http://jsfiddle.net/HB7LU/16771/';
}

Answer №3

A quick and easy way to open a link in a new tab:

 <a href="{{details.website}}" ng-click="openNewTab(details.website)"> 
    {{details.website}}
 </a>
     $scope.openNewTab = function (url) 
    {
      $window.open(url, '_blank');
     };

Make sure to include $window in your controller before using this method.

Answer №4

If you want to automate this process, consider creating a custom directive.

app.directive('redirect', function ($location, $window, $rootScope) {
    return {

        link: function (scope, element, attrs) {
            element.on("click", function () {
                if (!attrs.newtab || attrs.newtab == false) {
                    $location.path(attrs.redirect);
                    scope.$apply();
                }
                else {
                    var url = $location.absUrl().substring(0, decodeURIComponent($location.absUrl()).indexOf($location.path(), $location.absUrl().indexOf("#")) + 1) + attrs.redirect;
                    $window.open(url);
                }
            });
        }
    }
}

To utilize this in your HTML code and open a link in a new tab, use the following syntax:

<a redirect="/products/details" newtab="true">Open in new tab</a>

Answer №5

After implementing this solution for Angular 4 and above, I can confirm that it works successfully:


<button mat-menu-item>
    <a href="/faq/" target="_blank" style="color: inherit; text-decoration: none;">
        <mat-icon>help</mat-icon>FAQ
    </a>
</button>

To achieve the desired result, I had to reset the color to default settings and override the browser's color scheme. It was gratifying to see that this approach still maintained the ripple effect without any additional JavaScript code needed.

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

Reorganize items that extend beyond the list into the next column using Bootstrap

I have a row with two columns, where Column 1 currently contains 7 list items under the ul tag. However, I want to display only 5 list items in Column 1 and automatically move the remaining items to the next column (i.e., Column 2). Is there a way to ach ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

Implementing $http in AngularJS

I am encountering the following issue: angular.module('myApp').factory('dashboard', ['$http', function ($http) { return { name: function(str){ return str + ':' + 'works!'; ...

Retrieve the background image by calling $('#id').attr('src')

How can I access the background image of a div using jQuery? I attempted: var img = $('#id').attr('src'); however, alert(img) displays as null / undefined. I also experimented with document.getElementById('elementId').src ...

Tips for successfully passing ExpressJS locals variable to an EJS template and utilizing it as a parameter when invoking a JavaScript function during the onload HTML event

const hostname = "192.168.8.154"; const port = 3002; app.use('*', function (req, res, next) { db.collection('sys_params').find().toArray() .then(sysParams => { //console.log(sysParams); app.locals.sysParams ...

Learn the process of adjusting opacity for a specific color in CSS

At the moment, this is the code I'm using to apply a color to an element using jss. const styleSheet = theme => ({ root: { backgroundColor: theme.colors.red, }, }) I am interested in finding out if there is a way to add opacity based o ...

Sorting by alphabetical order using Vue.js and Axios

I am currently in need of assistance with filtering my data based on brand name and then further refining the results by alphabetical order using the "product.name" property. Provided below are the axios functions I am using for this task. export default { ...

Tips for effectively closing div elements

How can I modify this accordion to close when a user clicks on another link, and also change the image of the open "p" tag? Currently, clicking on a link toggles the content and changes the image. However, what I am struggling with is closing the previousl ...

React- Input value disappears after submission

Implementing validation for email-based input has been a bit of a challenge for me. I have managed to set up the debounce function for onChange event handling, but encountered a strange issue. The problem arises when the user submits an invalid string bef ...

Failing to complete a field in the form does not generate an error message when submitted [AngularJS]

My code is designed to display an error message if the user clicks the submit button without filling in a field. However, the functionality is currently not working as intended. <form name="loginForm" ng-submit="loginForm.$valid && login()" n ...

When I click the login button, a .ttf file is being downloaded to my computer

I have encountered an issue with my web application where custom font files in .ttf, .eot, and .otf formats are being downloaded to users' local machines when they try to log in as newly registered users. Despite attempting various solutions, I have b ...

The variable ReactFauxDOM has not been declared

Exploring the combination of D3 and React components. Utilizing OliverCaldwell's Faux-DOM element has led me to encounter a frustrating error message stating "ReactFauxDOM is not defined”. Despite following the npm install process correctly... It s ...

Ways to extract information from a URL when utilizing JQuery code

Code snippet: $(document).ready(function(){ $(".uni_type").click(function(){ uni_type = this.id; location.href = "filter-colleges.php?uni_type="+uni_type; }); }); HTML code: <ul> <li class="uni_type" id="central univ ...

The functionality of .on is disrupted by a dynamically generated table through ajax

I am currently using ajax to dynamically generate a table. Once a user inputs a query, a new table containing data is created and replaces the existing content within #content-display: function searchQuery(query){ $.ajax({ url: "search.php", ...

Using an if statement to run a script in Npm

Is there a way to configure an npm run script to use different AWS accounts based on the environment? { "config": { "acc": if ({npm_config_env} == "dev") "account1" else "account_2" }, "scr ...

What is the method for achieving the equivalent effect of "background-size: cover" on an <img>?

I am looking to ensure that an <img> has the smallest possible size without any empty spaces inside a div, while also being perfectly centered both horizontally and vertically. The image size may vary. To better illustrate, here is an example: http: ...

Resolving issues with jQuery's live() method while incorporating AJAX calls

One of the challenges I'm facing is with buttons on a webpage that are part of the class "go". The code snippet below demonstrates how I handle actions related to these buttons: $(".go").live('click', this.handleAction); The issue arises w ...

Issue with Checkbox Filtering Function [ReactJS]

I'm working on setting up a checkbox filtering feature in React. Here's what I want to achieve: User goes to the products page where all products are displayed initially. User checks a checkbox and only filtered products should be shown. If use ...

Node.js is the perfect platform for streaming videos effortlessly

I'm attempting to live stream a video from my server, but it seems like I may be doing something wrong: Here is how my routes are defined: var fs = require('fs'); router.get('/', function(req, res) { fs.readdir(__dirname + &ap ...