如何在AngularJS中重新定位刷新的不同视图?

时间:2022-10-29 19:39:58

i'm developing an application in AngularJS. Basically, i have a "home" page and a "new project". In the home page i have a menu with a link to "new project".

我正在AngularJS中开发一个应用程序。基本上,我有一个“主页”页面和一个“新项目”。在主页中,我有一个菜单,其中包含“新项目”的链接。

I configured the $stateProvider as follows :

我配置$ stateProvider如下:

$stateProvider.state('home', {
    url: '/',
    templateUrl: 'partials/home.jsp'
}).state('newproject', {
    url: '/newproject',
    templateUrl: 'partials/new-project.html'
})

So, when i enter the app, i'm in the home page. Then i click on "new project" link and i'm in the "new project" page. Now the url is http://myapp/newproject

所以,当我进入应用程序时,我在主页。然后我点击“新项目”链接,我在“新项目”页面。现在网址是http:// myapp / newproject

My problem is, when i refresh the page, i want to be redirected on the home page, even if the url in my browser bar is still http://myapp/newproject

我的问题是,当我刷新页面时,我想在主页上重定向,即使浏览器栏中的URL仍然是http:// myapp / newproject

How can i achieve that?

我怎样才能实现这一目标?

UPDATE :

更新:

Thank you very much squiroid for your answer. I used the second solution and it worked like a charm. A little clarification, just in case someone should have the same problem, before redirecting to home you have to prevent default operation. So the correct working code is :

非常感谢你的回答。我使用了第二种解决方案,它就像一个魅力。稍微澄清,以防万一有人应该有同样的问题,在重定向到家之前你必须防止默认操作。所以正确的工作代码是:

$rootScope.$on("$locationChangeStart", function(event, next, current) { 

if(next==current && next=='/newproject')
    event.preventDefault();
    $state.go('home');

});

});

1 个解决方案

#1


14  

Use this in your controller of 'newproject' it is listening your refresh:

在“newproject”的控制器中使用它,它正在监听你的刷新:

$rootScope.$on('$locationChangeStart', function(event) {
     $state.go('home');
});

or put this in app.run();

或者把它放在app.run();

$rootScope.$on("$locationChangeStart", function(event, next, current) { 

    if(next==current && next=='/newproject')
        $state.go('home');

});

#1


14  

Use this in your controller of 'newproject' it is listening your refresh:

在“newproject”的控制器中使用它,它正在监听你的刷新:

$rootScope.$on('$locationChangeStart', function(event) {
     $state.go('home');
});

or put this in app.run();

或者把它放在app.run();

$rootScope.$on("$locationChangeStart", function(event, next, current) { 

    if(next==current && next=='/newproject')
        $state.go('home');

});