Open a new tab on button click in AngularJS
Asked Answered
J

4

78
<button type="button" class="btn btn-primary" ng-click="openTab()">new tab</button>

openTab = function () {
  $http.post('www.google.com');
}

What I want is post a require and open the response html in a new tab when you click the "openTab" button. There is no method to do this with $http. I think this maybe simple, but I can't find a way.

Jorgejorgensen answered 20/7, 2013 at 1:43 Comment(1)
Can you accept the solution ? My vote is for @Lipography one :)Josephjosepha
L
178

You can do this all within your controller by using the $window service here. $window is a wrapper around the global browser object window.

To make this work inject $window into you controller as follows

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

this works well when redirecting to dynamic routes

Lipography answered 22/8, 2014 at 5:29 Comment(2)
Chrome locks this popup.. How can I recognize it's locked and inform user about it?Prelect
its working fine in chrome and firefox but in IE user get loggedout and redirected to login page.is there some work around to solve the issue for IEShufu
J
21

I solved this question this way.

<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>

$scope.openTab = function() {
    $scope.url = 'www.google.com';
}
Jorgejorgensen answered 8/11, 2013 at 4:29 Comment(1)
This trick is excellent, especially for someone is dealing with the problem that Chrome's security can lock the new tab page which is opened by script manually.Manysided
M
7

Proper HTML way: just surround your button with anchor element and add attribute target="_blank". It is as simple as that:

<a ng-href="{{yourDynamicURL}}" target="_blank">
    <h1>Open me in new Tab</h1>
</a>

where you can set in the controller:

$scope.yourDynamicURL = 'https://stackoverflow.com';
Mesomorph answered 30/8, 2018 at 23:22 Comment(0)
E
-1

You should use the $location service

Angular docs:

Era answered 23/9, 2013 at 15:46 Comment(1)
location doesn't allow you to open a new tab.Troxell

© 2022 - 2024 — McMap. All rights reserved.