AngularJS UI 路由器 - 在不重新加载状态的情况下更改 url路由器、情况下、加载、状态

2023-09-06 08:20:29 作者:唯我长生

目前我们的项目正在使用默认的$routeProvider,我正在使用这个hack",在不重新加载页面的情况下更改url:

Currently our project is using default $routeProvider, and I am using this "hack", to change url without reloading page:

services.service('$locationEx', ['$location', '$route', '$rootScope', function($location, $route, $rootScope) {
    $location.skipReload = function () {
        var lastRoute = $route.current;
        var un = $rootScope.$on('$locationChangeSuccess', function () {
            $route.current = lastRoute;
            un();
        });
        return $location;
    };
    return $location;
}]);

控制器

$locationEx.skipReload().path("/category/" + $scope.model.id).replace();

我正在考虑用 ui-router 替换 routeProvider 来嵌套路由,但在 ui-router 中找不到这个.

I am thinking of replacing routeProvider with ui-router for nesting routes, but cant find this in ui-router.

有可能 - 对 angular-ui-router 做同样的事情吗?

Is it possible - do the same with angular-ui-router?

我为什么需要这个?让我用一个例子来解释:创建新类别的路径是 /category/newclicking 上 SAVE 我显示 success-alert 并且我想将路由 /category/new 更改为 /caterogy/23 (23 - 是存储在 db 中的新项目的 id)

Why do I need this? Let me explain with an example : Route for creating new category is /category/new after clicking on SAVE I show success-alert and I want to change route /category/new to /caterogy/23 (23 - is id of new item stored in db)

推荐答案

只需使用 $state.transitionTo 代替 $state.go . $state.go 在内部调用 $state.transitionTo 但自动将选项设置为 { location: true, inherit: true, relative: $state.$current, notify:真}.您可以调用 $state.transitionTo 并设置 notify: false .例如:

Simply you can use $state.transitionTo instead of $state.go . $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true } . You can call $state.transitionTo and set notify: false . For example:

$state.go('.detail', {id: newId}) 

可以替换为

$state.transitionTo('.detail', {id: newId}, {
    location: true,
    inherit: true,
    relative: $state.$current,
    notify: false
})

正如 fracz 所建议的,它可以简单地是:

As suggested by fracz it can simply be:

$state.go('.detail', {id: newId}, {notify: false})