使用 window.location.href 的 ngClick 登陆重定向两次

ngClick with window.location.href lands redirect twice

我的移动优先应用程序需要可点击的 table 行进行导航,它通过

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

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

table 行调用 go_to 函数正常,但它在历史记录中两次登陆 #details/x 页面,其中第一次命中是持续重定向到下一个, 因此后退按钮变得无用。

IE:假设我们有两个页面; Main 和 Sub,其中 Main 具有 ng-click(go_to) 功能。在单击 ng-click 之前,浏览器历史记录如下所示 [Main]。点击后,它看起来像[Main, Sub, Sub]。反击,无论多少次,仍然会让你进入 Sub.

是否有任何连贯的解释为什么应用程序会这样?也非常欢迎其他解决方案

您应该像这样使用 $location 服务....

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

同时修正你的语法。

由于您在 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() 中的更改将导致向用户显示正确的路线。

我的 webapp 也有同样的问题,唯一的区别是我使用 ngNewRouter 并在配置中定义组件。对我来说,当我点击 table 行时,浏览器(IE11)在我从 window.location.href=#/newpath 或 $window.location.href=#/newpath javascript。