Open a new tab on button click in AngularJS

JavascriptAngularjs

Javascript Problem Overview


<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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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';
}

Solution 3 - Javascript

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';

Solution 4 - Javascript

You should use the $location service

Angular docs:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneptuneView Question on Stackoverflow
Solution 1 - JavascriptAaronView Answer on Stackoverflow
Solution 2 - JavascriptneptuneView Answer on Stackoverflow
Solution 3 - JavascriptRenat GatinView Answer on Stackoverflow
Solution 4 - JavascripttetotechyView Answer on Stackoverflow