Angularjs open in new window

A common requirement!

In AngularJS, you can use the $window service to open a link in a new window. Here are a few ways to do it:

Method 1: Using $window.open()

$scope.openInNewWindow = function() {
  $window.open('https://www.example.com', '_blank');
};

In this example, we define a function openInNewWindow that uses the $window.open() method to open a new window with the URL https://www.example.com. The _blank parameter specifies that the link should be opened in a new window.

Method 2: Using target attribute

<a rel="nofollow" target="_blank" href="https://www.example.com" target="_blank">Open in new window</a>

In this example, we use the target attribute on an <a> tag to specify that the link should be opened in a new window.

Method 3: Using $templateCache and $sce

$scope.openInNewWindow = function() {
  var url = 'https://www.example.com';
  var template = '<a rel="nofollow" target="_blank" href="' + url + '" target="_blank">Open in new window</a>';
  $templateCache.put('newWindowTemplate', template);
  $sce.trustAsHtml(template);
  $compile(template)($scope);
};

In this example, we create a template string that contains an <a> tag with the target attribute set to _blank. We then use the $templateCache service to store the template, and the $sce service to trust the HTML as safe. Finally, we use the $compile service to compile the template and render it on the page.

Method 4: Using a directive

angular.module('myApp').directive('openInNewWindow', function($window) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('click', function() {
        $window.open(attrs.href, '_blank');
      });
    }
  };
});

In this example, we define a directive openInNewWindow that listens for clicks on an element with the directive applied. When the element is clicked, it uses the $window.open() method to open a new window with the URL specified in the href attribute.

These are just a few examples of how you can open a link in a new window in AngularJS. Choose the method that best fits your use case!