小编典典

状态更改时,如何防止在命名视图上重新加载?AngularJS UI路由器

angularjs

ui-router在应用程序中使用了出色的模块。作为此过程的一部分,我使用命名视图来管理应用程序中的“动态子导航”。

考虑以下:

$urlRouterProvider.otherwise('/person/list');

$stateProvider
    .state('person', {
        url: '/person',
        abstract: true,
    })
    .state('person.list', {
        url: '/list',
        views: {
            "main@": {
                templateUrl: "person.list.html",
                controller: 'PersonListController'
            }
        }
    })
    .state('person.details', {
        url: '/{id}',
        views: {
            'main@': {
                templateUrl: "person.details.html",
                controller: 'PersonController'
            },
            'nav@': {
                templateUrl: "person.nav.html",
                controller: 'PersonNavController'
            }
        }
    });

用户首次访问该应用程序时,系统会向他们显示人员列表。当他们单击某个人时,他们将被带到详细信息页面。很基本的东西。如果有帮助,这是标记…

<div>
    <aside ui-view="nav"></aside>
    <div ui-view="main"></div>
</div>

但是,PersonNavController调用REST服务以获取人员列表,因此在查看人员时,用户可以导航同级元素。使用上述方法会导致模板和控制器重新呈现,因此每次单击后都会产生延迟,尽管内容永远不会改变。

有没有一种方法可以保持'nav@'视图加载并仅刷新'main@'视图?


阅读 334

收藏
2020-07-04

共1个答案

小编典典

ui-router在这种情况下,我使用的方式是: 将视图移动到最小公分母

换句话说:如果ui-view="nav"所有细节都共享并且所有细节都相同 (因为它应该只被加载一次) -它应该是list状态的一部分(状态的
父对象detail

父状态的定义将如下调整:

.state('person.list', {
    url: '/list',
    views: {
        "main@": {
            templateUrl: "person.list.html",
            controller: 'PersonListController'
        }
        // here we target the person.list.html
        // and its ui-view="nav"
        'nav@person.list': {
            templateUrl: "person.nav.html",
            controller: 'PersonNavController'
        }
    }

那么诀窍在哪里?在角的力量ui-router。我们可以 在每个状态定义期间当前
视图作为目标。现在,该nav视图是list状态定义的一部分-即,在细节切换期间不会重新加载该视图

我们只需要使用定义的命名约定,请参阅:

提到的文档中很少有引用的行:

views: {
    ////////////////////////////////////
    // Relative Targeting             //
    // Targets parent state ui-view's //
    ////////////////////////////////////

    // Relatively targets the 'detail' view in this state's parent state, 'contacts'.
    // <div ui-view='detail'/> within contacts.html
    "detail" : { },

    // Relatively targets the unnamed view in this state's parent state, 'contacts'.
    // <div ui-view/> within contacts.html
    "" : { },

    ///////////////////////////////////////////////////////
    // Absolute Targeting using '@'                      //
    // Targets any view within this state or an ancestor //
    ///////////////////////////////////////////////////////

    // Absolutely targets the 'info' view in this state, 'contacts.detail'.
    // <div ui-view='info'/> within contacts.detail.html
    "info@contacts.detail" : { }

    // Absolutely targets the 'detail' view in the 'contacts' state.
    // <div ui-view='detail'/> within contacts.html
    "detail@contacts" : { }
2020-07-04