AngularJS:具有路由的多个视图,不会丢失范围

Kei*_*ith 12 angularjs angularjs-scope angularjs-routing

我正在尝试实现经典的列表/细节UI.单击列表中的项目时,我想显示该项目的编辑表单,同时仍显示列表.我正在尝试解决Angular的每页1个视图限制,并决定将所有URL路由到同一个控制器/视图.(也许这是我问题的根源,我对其他选择持开放态度.)

路由:

$routeProvider
    .when('/list', { templateUrl: '/Partials/Users.html', controller: UserController })
    .when('/edit/:UserId', { templateUrl: '/Partials/Users.html', controller: UserController })
    .otherwise({ redirectTo: '/list' });
Run Code Online (Sandbox Code Playgroud)

视图(/Partials/Users.html):

<!-- List of users -->
<div ng-repeat="user in Users">
    <a href="*/edit/{{ user.Id }}">Edit {{ user.Name }}</a>
</div>

<!-- Edit form -->
<div>
    {{ SelectedUser.Name }}
</div>
Run Code Online (Sandbox Code Playgroud)

控制器:

function UserController($scope, $routeParams) {
    // the model for the list
    $scope.Users = GetUserListFromService();

    // the model for the edit form
    if ($routeParams.UserId != null)
        $scope.SelectedUser = GetUserFromService($routeParams.UserId);
}
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 单击编辑链接时,控制器将使用新范围重新实例化,因此我必须重新初始化"用户"列表.(在一个更复杂的例子中,我可以从存储绑定到模型的用户输入,这也会丢失.)我宁愿保留前一个路径的范围.
  2. 我更喜欢使用一个单独的控制器(或者,正如许多其他Angular开发人员所抱怨的那样,能够拥有多个显示的视图!)但这会导致同样的失去范围的问题.

And*_*lin 14

尝试使用ui-router:http://github.com/angular-ui/ui-router.

与角度默认路由相比,它们具有嵌套视图和更简单的状态管理:-)

  • @timothy https://github.com/dotJEM/angular-routing是UI-Router的替代方案,它有一个简单的视图方法(没有神奇的东西与视图@视图等...只是纯粹和简单的命名所有视图)...如果这是你的麻烦的原因(UI-Router视图模型已经收到了相当多的批评,并且很多人似乎很难在非常简单的情况下使用它) (2认同)

art*_*tch 7

核心AngularJS不支持多个视图.您可以使用此库来支持页面上任意数量的嵌套视图,其中每个级别都使用自己的控制器和模板独立配置:

http://angular-route-segment.com

它比ui-router更简单易用.示例配置可能如下所示:

$routeSegmentProvider.

when('/section1',          's1.home').
when('/section1/prefs',    's1.prefs').
when('/section1/:id',      's1.itemInfo.overview').
when('/section1/:id/edit', 's1.itemInfo.edit').
when('/section2',          's2').

segment('s1', {
    templateUrl: 'templates/section1.html',
    controller: MainCtrl}).

within().

    segment('home', {
        templateUrl: 'templates/section1/home.html'}).

    segment('itemInfo', {
        templateUrl: 'templates/section1/item.html',
        controller: Section1ItemCtrl,
        dependencies: ['id']}).

    within().

        segment('overview', {
            templateUrl: 'templates/section1/item/overview.html'}).

        segment('edit', {
             templateUrl: 'templates/section1/item/edit.html'}).

        up().

    segment('prefs', {
        templateUrl: 'templates/section1/prefs.html'}).

    up().

segment('s2', {
    templateUrl: 'templates/section2.html',
    controller: MainCtrl});
Run Code Online (Sandbox Code Playgroud)