2015-06-10 39 views
1

我移动第一应用需要用于导航可点击表中的行,其通过ngClick与window.location.href土地重定向两次

<tr ng-repeat="foo in bar" ng-click="go_to(foo.id)" > 

解决()函数是在控制器范围内定义如The go_to:

$scope.go_to = function (in_id) { 
    var url = "#details/" + in_id; 
    window.location.href = url; 
}; 

而且#details通过ngRoute路由:

.when('/details/:id', { 
      templateUrl : 'foo.html', 
      controller : 'fooController' 
     }) 

的表 - 行很好地调用了go_to函数,但它在历史记录中重复两次#details/x页面,其中第一个命中是常量重定向到下一个,所以后退按钮变得无用。 IE:假设我们有两页; Main和Sub,其中Main具有ng-click(go_to)功能。在单击ng之前,浏览器历史记录看起来像[Main]。点击后,它看起来像[Main,Sub,Sub]。反击,无论次数如何,都会让你着迷于Sub。

有没有任何连贯的解释为什么应用程序的行为是这样的?它的所有替代方案也非常欢迎

+1

是否有任何不使用$ location服务的理由? – TMichel

+0

是的。愚蠢显然 – JonasR

+0

不要太自己:)不管怎样,欢迎来到SO! – TMichel

回答

4

由于您使用的是Angular应用程序,因此使用window.location.href更改页面并不是正确的做法,因为它会有效地导致整个页面重新加载,因此您的整个Angular应用程序将被重新加载。你有什么是一个单页面的应用程序,你应该这样对待,即。除非你绝对必须避免重新加载页面。

因此,推荐的做法是使用$location服务来更改显示给用户的页面。像

$scope.go_to = function (in_id) { 
    var url = "#details/" + in_tg_id; 
    $location.url(url); 
}; 

$route服务手表$location.url()(根据它的文档),因此在一个$location.url()变化将导致正确的路由要被显示给用户。

+0

太棒了,谢谢! – JonasR

3

你应该使用这样的$位置服务....

$scope.go_to = function (in_id) { 
    var url = "/details/" + in_id; 
    $location.path(url); 
}; 

而且解决您的语法。

0

我的webapp中也有同样的问题,唯一的区别是我使用ngNewRouter并在配置中定义组件。对于我来说,当我点击表格行时,浏览器(IE11)在我做window.location.href =#/ newpath或$ window.location.href =#/ newpath时至少停留6-7秒。