angular.js链接行为 – 禁用特定url的深层链接

我有一个启用了HTML5模式的工作Angular.js应用程序。

$location.Html5mode(true).hashbang("!"); 

我想实现的是获取一些URL或<a>标签来执行正常的浏览行为,而不是使用HTML5历史API更改地址栏中的URL并使用Angular控制器处理它。

我有这个链接:

 <a href='/auth/facebook'>Sign in with Facebook</a> <a href='/auth/twitter'>Sign in with Twitter</a> <a href='/auth/...'>Sign in with ...</a> 

我希望浏览器将用户redirect到/auth/...这样用户将被redirect到authentication服务。

有什么办法可以做到这一点?

在Angular 1.0.1中添加target="_self"

 <a target="_self" href='/auth/facebook'>Sign in with Facebook</a> 

这个function被logging( https://docs.angularjs.org/guide/$location – search'_self')

如果你好奇,看看angular度来源(5365 @ v1.0.1行)。 只有当!elm.attr('target')为真时才会发生点击劫持。

Fran6co方法的替代方法是禁用$ locationProvider中的“rewriteLinks”选项:

 $locationProvider.html5Mode({ enabled: true, rewriteLinks: false }); 

这将完成与调用$ rootElement.off('click')完全相同的事情,但不会干扰处理应用根元素上的单击事件的其他javascript。

请参阅文档和相关来源

这是全部closures深度链接的代码。 它禁用rootElement中的单击事件处理程序。

 angular.module('myApp', []) .run(['$location', '$rootElement', function ($location, $rootElement) { $rootElement.off('click'); }]); 

我已经有几次碰到同样的问题了,而且我提出了两个function性的解决scheme,但都觉得自己像是黑客,而不是非常“有棱angular的”。

黑客#1:

绑定一个window.location刷新到链接的click事件。

 <a href=/external/link.html onclick="window.location = 'http://example.com/external/link.html';" > 

这种方法的缺点和问题相当明显。

黑客#2

设置angular色$route执行$window.location更改。

 // Route .when('/external', { templateUrl: 'path/to/dummy/template', controller: 'external' }) // Controller .controller('external', ['$window', function ($window) { $window.location = 'http://www.google.com'; }]) 

我想你可以扩展这个使用$routeParams或查询string有一个控制器处理所有“外部”链接。

正如我所说,这些解决scheme都不是很满意,但是如果你必须在短期内做到这一点,他们可能会有所帮助。

在一个侧面说明,我真的很想看到这种types的function的Angular支持rel=external ,就像jQueryMobile使用它来禁用Ajax页面加载。

为了解决Nik的答案,如果你有很多链接,并且不想为它们中的每一个添加目标,你可以使用一个指令:

 Module.directive('a', function () { return { restrict: 'E', link: function(scope, element, attrs) { element.attr("target", "_self"); } }; }); 

要添加到Dragonfly的答案,我发现限制target =“_ self”属性的最佳做法是不要将ng-app属性放在body标签上。 通过这样做,你可以告诉angular色身体标签中的所有内容都是angular度应用程序的一部分。

如果你在一个不受angular度影响的静态包装中工作,把你的ng-app属性放在一个div(或者其他元素)上,而这个div只包含angular色应用将要工作的位置。这样,必须把target ='_ self'属性放在ng-app元素的子元素的链接上。

 <body> ... top markup ... <div ng-app="myApp"> <div ng-view></div> </div> ... bottom markup ... </body> 

在你的路线尝试:

$routeProvider.otherwise({})