简体   繁体   English

不执行routeprovider的角度更改网址

[英]Angular change url without executing routeprovider

I'm trying to make facebook-like modal windows - for example you click on image and it opens in modal window and the url changes from / to /img/dj27s_D without rerendering the views and when you close the modal the url goes back to / . 我正在尝试制作类似Facebook的模式窗口-例如,您单击图像并在模式窗口中打开,并且URL从/更改为/img/dj27s_D而不重新渲染视图,而当您关闭模式时,URL返回至/

I figured out that using 我发现使用

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

will just crash the application on the next $digest . 只会在下一个$digest崩溃应用程序。 I have also tried 我也尝试过

$location.path = '';

but nothing happens. 但什么也没发生。 If I execute 如果我执行

$location.path('/img/id')

The $routeProvider will kick in and change the views. $ routeProvider将加入并更改视图。 I dont want this to happen, just want to temporary change the url while the modal is opened. 我不希望发生这种情况,只想在打开模式时临时更改URL。

You can set the router to use the previous route. 您可以将路由器设置为使用先前的路由。 For example this way in your controller: 例如,在您的控制器中以这种方式:

lastRoute = $route.current;
$scope.$on('$locationChangeSuccess', function (e) {
  if (window.location.href.match(/\/view/) || window.location.href === '/') {
    $route.current = lastRoute;
  }
});

When $route.current does not change, full page refresh is not triggered. 如果$route.current不变,则不会触发整页刷新。 You might wish to do some regexp checks to keep your URL space tidy to prevent refresh, but it's a small price to pay. 您可能希望进行一些正则表达式检查,以保持URL空间整洁以防止刷新,但这是一个很小的代价。

I recommend looking at the Angular UI-Router . 我建议看Angular UI-Router You might be able to do what you're describing with a nested state / nested view, where the inner view pops up the modal. 您可能可以使用嵌套状态/嵌套视图来执行您要描述的内容,其中内部视图会弹出模态。 You can configure the URLs for each state as you want. 您可以根据需要为每个州配置URL。

Edit: There may be a way without using UI-Router, but I haven't done that. 编辑:也许有一种不用UI-Router的方法,但是我还没有做到这一点。 Perhaps this other SO question is relevant to you. 也许这另一个SO问题与您有关。

A simple partial example of UI Router with a nested view, you'd put this in your controller: 一个带有嵌套视图的UI Router的简单部分示例,您可以将其放在控制器中:

$stateProvider.state('site', {
    url: "",
    templateUrl: 'app/parent.tpl.html',
    controller: 'ParentCtrl'
});

$stateProvider.state('site.child', {
    url: "/child",
    templateUrl: 'app/child.tpl.html',
    controller: 'ChildCtrl'
});

Then in the parent template, put this type of div: 然后在父模板中,放入以下类型的div:

<div ui-view></div>

which will be where the child template will load within the parent template. 这将是子模板将在父模板中加载的位置。 In the child template, you could try the modal dialog. 在子模板中,您可以尝试模式对话框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM