AngularJs - Open url in new tab

I have an application with a public page and an admin page. I would like open the admin page in a new tab after login. I've tried this, after the login was successful, but to no effect. The public page (where the login is) is just being reloaded:

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

Any tips would be appreciated. Thank you.

Answers:

Answer

Here is a working JSFiddle, you have to inject $window before you can use it:

JS:

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

HTML:

<div ng-app="myApp" ng-controller="dummy"> 
    <a ng-href="" ng-click="redirectToGoogle()">Hello</a>
</div>
Answer

Here's another working JSFiddle

HTML:

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

JS:

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

A simple method to open link in new tab,

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

Before using it you should inject $window in your controller.

Answer

You can have a directive to do this for you.

directives.redirect = function ($location, $window, $rootScope) {
    return {

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

And in HTML, you can use the following to open in a new tab:

<a redirect="/admin/overview" newwindow="true">Open in new tab</a>
Answer

I used this and it works (angular4+): <button mat-menu-item> <a href="/faq/" target="_blank" style="color: inherit; text-decoration: none;"> <mat-icon>help</mat-icon>FAQ </a> </button>

I had to restore color to default and override browser's colors. This still gives me the ripple effect and everything with zero javascript code.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.