AngularJs - 在新标签页中打开链接

19

我有一个包括公共页面和管理页面的应用程序。我想在登录后在新标签页中打开管理页面。我尝试过在登录成功后执行以下操作,但没有效果。公共页面(登录页面)只是被重新加载:

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

有任何建议都非常感激。 谢谢。


1
你能否在 fiddle 中重现该错误并将链接发布在这里? - Alekos Filini
很遗憾,我无法在fiddle中准确地重现代码。它太复杂了。 - VictorB
“/admin/overview”是一个路由名称吗?因为根据文档,您不能在URI中使用该方法(http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state)。这可能是问题的一部分。 - user1334319
是的,这是一个路由名称。这可能是问题的原因。但我找不到带有路由的示例,所以我只是尝试了一下。 - VictorB
我之前发布的链接展示了几个带有路由名称的示例,这基本上是使用此方法($state.href)的唯一方式。 - user1334319
工作示例:https://jsfiddle.net/aniket_kulkarni/wdzjcgeL/ - Aniket Kulkarni
5个回答

37

以下是一个可用的 JSFiddle,在使用之前必须先注入$window

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>

1
这在使用外部URL(如您提供的那个)时非常有效,但在尝试使用router-ui状态(或url)时,它不起作用。 - VictorB

16

这里是另一个可以使用的 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/';
}

2

一种简单的在新标签页中打开链接的方法:

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

在使用它之前,您应该在控制器中注入$window

2
你可以使用指令来完成此操作。

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

在HTML中,您可以使用以下内容在新选项卡中打开链接:
<a redirect="/admin/overview" newwindow="true">Open in new tab</a>

这是一个可用的示例:https://jsfiddle.net/aniket_kulkarni/wdzjcgeL/ - Aniket Kulkarni
你的解决方案是在_blank URL中放置#。使用此$location.$$absUrl.split('#')[0] + attrs.redirect; - PSA

-1
我使用了这个,它可以工作(angular4+): <button mat-menu-item> <a href="/faq/" target="_blank" style="color: inherit; text-decoration: none;"> <mat-icon>help</mat-icon>常见问题解答 </a> </button> 我必须将颜色恢复为默认值并覆盖浏览器的颜色。这仍然可以给我带来涟漪效果和零JavaScript代码的所有内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接