AngularJs:重新加载页面

问题描述 投票:130回答:10
<a ng-href="#" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>

我想重新加载页面。我怎样才能做到这一点?

angularjs angularjs-scope
10个回答
260
投票

您可以使用reload服务的$route方法。在你的控制器中注入$route,然后在你的reloadRoute上创建一个方法$scope

$scope.reloadRoute = function() {
   $route.reload();
}

然后你可以在链接上使用它,如下所示:

<a ng-click="reloadRoute()" class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

此方法将导致当前路由重新加载。如果你想要执行完全刷新,你可以注入$window并使用它:

$scope.reloadRoute = function() {
   $window.location.reload();
}

稍后编辑(ui-router):

正如JamesEddyEdwards和Dunc在他们的答案中所提到的,如果你使用的是angular-ui/ui-router,你可以使用以下方法重新加载当前状态/路由。只需注入$state而不是$route然后你有:

$scope.reloadRoute = function() {
    $state.reload();
};

0
投票

Angular 2+

我在搜索Angular 2+时发现了这个,所以这里是这样的:

.config(['$routeProvider', function($routeProvider) {
     $routeProvider.when('/first-page', {
         templateUrl: '/first-template',
         controller: 'SomeCtrl'
     }).when('/another-route', {//this is the new "when"
         redirectTo: '/first-page'
     });
}])

51
投票

qazxsw poi对象是通过qazxsw poi服务为qazxsw poi提供的,你可以使用类似的东西:

window

而且:

$window

作为旁注,我不认为$ route.reload()实际上重新加载页面,但easier testing and mocking


18
投票
$scope.reloadPage = function(){$window.location.reload();}

诀窍。

<a ng-click="reloadPage"  class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

不需要路线或任何简单的旧js


14
投票

与亚历山大的答案类似,但使用$ state而不是$ route:

(来自JimTheDev的SO回答only the route。)

 location.reload(); 

9
投票

如果使用Angularjs更高级的qazxsw poi,我肯定会推荐,那么你现在可以简单地使用:

<a ng-click="reload()">

$scope.reload = function()
{
   location.reload(); 
}

这与Dunc的回答基本相同。


2
投票

我避免无限循环的解决方案是创建另一个进行重定向的状态:

here

1
投票

只需使用$scope.reloadState = function() { $state.go($state.current, {}, {reload: true}); } <a ng-click="reloadState()" ... 就好了(不要忘记将$ route注入你的控制器),但是从你的例子中你可以使用“href”代替“ng-href”:

ui-router

您只需要使用ng-href来保护用户免受因Angular替换{{}}标记内容之前单击而导致的无效链接。


1
投票

在Angular 1.5上 - 在尝试上述某些解决方案之后,只想重新加载没有完整页面刷新的数据时,我遇到了正确加载数据的问题。我注意到,当我去另一条路线然后我回到当前,一切正常,但是当我只想使用$state.reload(); 重新加载当前路线时,那么一些代码没有正确执行。然后我尝试以下列方式重定向到当前路由:

$stateProvider.state('app.admin.main', {
    url: '/admin/main',
    authenticate: 'admin',
    controller: ($state, $window) => {
      $state.go('app.admin.overview').then(() => {
        $window.location.reload();
      });
    }
  });

并在模块配置中,添加另一个$route.reload()

<a href=""  class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

它对我来说很好。它不会刷新整个页面,只会导致当前控制器和模板重新加载。我知道这有点笨拙,但这是我找到的唯一解决方案。


1
投票
$route.reload()

并在控制器中

$scope.someFuncName = function () {
    //go to another route
    $location.path('/another-route');
};

并在路线文件中

when

因此,如果在url中传递的id与通过单击锚点调用的函数的内容相同,则只需重新加载,否则请按照请求的路径进行操作。

如果这有帮助,请帮助我改进这个答案。任何,建议是受欢迎的。

© www.soinside.com 2019 - 2024. All rights reserved.