Check out our new training course on AngularJS for Flex Developers

Open a Link in a New Window with AngularJS - Approach 1

I was working on a client project, built with AngularJS, and we wanted to open another application in a new window. This is a simple, common task, that you can accomplish with an href and a target. But we wanted to look for the most Angular way to accomplish it. Triggering the link in Angular gave us the option to do logging, or other functionality, before the click occurs. I decided to write a series about the different ways to make this happen.

The Setup

First, add Angular to your Application:


<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>

Then, create an Angular Module and controller:


angular.module('test',[]);
angular.module('test').controller('someController',['$scope','$window', function($scope,$window){
}]);

Two elements are injected into the controller. $scope is the common service used to communicate between the view and the controller. $window gives you an Angular reference to the browser's window object. We'll use $window to open the new page.

Open the new page

This method will open a new page:


$scope.onButtonClick = function(){
$window.open('https://www.jeffryhouser.com');
}

A function named onButtonClick() is saved to the $scope. Inside the button, the $window.open() method is called. This will force the window to open the URL in a new window.

Now add some HTML:


<body ng-app="test">

<div ng-controller="someController">
<button ng-click="onButtonClick()" >Open Link Standard</button>
</div>

The ngApp tag is put on the body. The ngController is put on a div. A button inside the div uses ngClick to call the onButtonClick() method.

Load the app and you'll see something like this:

A boring UI; but click the button:

The link to my blog will open in a new tab, based on my default browser settings.

Play with the code here.

What is Next?

The next entry in this series will show you how to use a similar approach to submit a form into a new window. Then, I'll write an entry about holding off on opening the new window until after an asynchronous call is complete. The last part is where things start to get complicated; but bear with me. We'll get there quickly.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.