UI-Router - 更改$ state而不重新加载/重新加载页面

时间:2014-07-04 23:20:39

标签: angularjs angular-ui-router

我一直在查看这些页面(123)。我基本上想要更改$state,但我不希望页面重新加载。

我目前位于/schedules/2/4/2014页面,当我点击按钮并让网址变为/schedules/2/4/2014/edit时,我想进入编辑模式。

我的edit状态只是$scope.isEdit = true,因此无需重新加载整个页面。但是,我确实希望更改$state和/或url,以便在用户刷新页面时,它会以编辑模式启动。

我该怎么办?

3 个答案:

答案 0 :(得分:22)

参考:https://github.com/angular-ui/ui-router/wiki/Quick-Reference#statetransitiontoto-toparams--options

$state.transitionTo('yourState', params, {notify: false});

答案 1 :(得分:21)

对于此问题,您可以创建一个既不具有templateUrl也不controller的子状态,并且通常在states之间前进:

// UPDATED
$stateProvider
    .state('schedules', {
        url: "/schedules/:day/:month/:year",
        templateUrl: 'schedules.html',
        abstract: true, // make this abstract
        controller: function($scope, $state, $stateParams) {
            $scope.schedDate = moment($stateParams.year + '-' + 
                                      $stateParams.month + '-' + 
                                      $stateParams.day);
            $scope.isEdit = false;

            $scope.gotoEdit = function() {
                $scope.isEdit = true;
                $state.go('schedules.edit');
            };

            $scope.gotoView = function() {
                $scope.isEdit = false;
                $state.go('schedules.view');
            };
        },
        resolve: {...}
    })
    .state('schedules.view', { // added view mode
        url: "/view"
    })
    .state('schedules.edit', { // both children share controller above
        url: "/edit"
    });

这里有一个重要的concept,在ui-router中,当应用程序处于特定状态时 - 当状态为"活动" - 其所有祖先状态都是隐含的也是活跃的。

所以,在这种情况下,

  • 当您的应用程序从查看模式进入编辑模式时,其父状态schedules(及其templateUrlcontroller甚至resolve)仍将保留。
  • 由于祖先状态被隐式激活,即使正在刷新子状态(或直接从书签加载),页面仍将正确呈现。

答案 2 :(得分:0)

添加我的答案,因为我认为它与接受的答案足够不同,并且可能对其他人有用:

我有两个状态,beginview,并且有一些可选参数与view的URL同步,就像这样:

$stateProvider
    .state('begin',
        {
            url: '/',
            template: '<app-element></app-element>'
        })
    .state('view',
        {
            url: '/View?param1&param2&...&paramN',
            template: '<app-element></app-element>'
            params: {
               param1: {
                   value: null,
                   squash: true
               },
               ...
            }
        });

我尝试使用<app-element>同步参数时,$state.go的链接功能将运行。使用{notify: false, reload: false}对我不起作用。每次仍然运行链接功能。我使用的是0.2,所以dynamic也不是可用的param选项。我按照@ b0nyb0y的建议,将其转变为父母/子女关系,这种关系有效:

$stateProvider
    .state('app',
        {
            url: '/',
            template: '<app-element></app-element>'
        })
    .state('app.view',
        {
            url: 'View?param1&param2&...&paramN',
            params: {
               param1: {
                   value: null,
                   squash: true
               },
               ...
            }
        });
相关问题