单击 link 时强制重新加载 route/state

Force reload route/state on link click

目前我正在做这样的事情

link.on('click', function () {
    if (link.attr('href') !== $route.current.originalPath)
        return;
    $route.reload();
});

我不知道有副作用,但我想可能会有一些。

在 ngRoute 中是否有更直接的方法来处理这个问题,例如通过 $location?

在 UI 路由器中执行相同操作的方法是什么时候更新应用程序以使用它?

对于 UI-Router,我们有一组选项,其中之一是 {reload: true}

go(to, params, options)

  • location - {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record.
  • inherit - {boolean=true}, If true will inherit url parameters from current url.
  • relative - {object=$state.$current}, When transitioning with relative path (e.g '^'), defines which state to be relative from.
  • notify - {boolean=true}, If true will broadcast $stateChangeStart and $stateChangeSuccess events.
  • reload (v0.2.5) - {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.

所以我们可以强制重新加载状态:

$state.go("stateName", stateParams, {reload: true});

您的代码可以转换为以下更改 $route.reload()$state.reload()

代码

link.on('click', function () {
    if (link.attr('href') !== $route.current.originalPath)
        return;
    //though this will not reload the controller content
    $state.reload(); //will force to reload state..
    $scope.$apply(); //needed here to tell angular js to run digest cycle.
});

git-hub issue 看来 $state.reload() 重新加载状态,但控制器没有重新实例化。为此,您需要使用以下代码而不是 $state.reload()

$state.transitionTo('tab.locations', $state.$current.params, { 
  reload: true, inherit: true, notify: true 
});

我发现这是使用 UI-router 的最短路径:

$state.go($state.current, {}, {reload: true});

或者您可以这样做:

$state.transitionTo($state.current, $stateParams, {
       reload: true,
       inherit: false,
       notify: true
     });

如果您正在使用 Ui.Router:

link.on('click', function (event) {
    if (link.attr('href') !== $route.current.originalPath)
        return;
  
    event.preventDefault();
    
    return $scope.$apply(function() {
      return $state.reload(); // $state.go($state.current.name, $stateParams, { inherit: false, reload: true, notify: true });
    });
});

如果您使用简单的 ngRoute,您必须从 templateCache 中删除 currentTemplate 和 $ 中的 return $route.reload()超时!