【问题标题】:Angular-ui-router loading same template with different parametersAngular-ui-router 加载具有不同参数的相同模板
【发布时间】:2016-02-18 16:57:12
【问题描述】:

目标

我们有许多视图,我们想用相同的模板/控制器填充它们。他们每个人都应该收到一个id,它将被加载而不会影响其他控制器。我们不想在模板的.directive 中使用scope: { item: '=' } 双向绑定。想想以这种方式加载的数千个元素(在示例中我们只有两个元素)。

我们尝试了什么

我们开始使用多个视图/嵌套视图来进行救援。我们最终得到了一个版本,其中许多视图都加载相同的组件,但都加载相同的id,这不是预期的行为 因为我们想分别控制它们中的每一个,即在本例中单击标题并将其id 传递给content1 不应导致content2 也加载它。

(代码基于此示例:http://www.funnyant.com/angularjs-ui-router/

短代码

index.html

<div ui-view="header"></div>
<div ui-view="content1"></div>
<div ui-view="content2"></div>
<div ui-view="footer"></div>

script.js

  .state('app.shows', {
      url: 'shows',
      views: {
          'content1@': {
              templateUrl: 'shows.html',
              controller: function($scope, ShowsService) {
                $scope.shows = ShowsService.list();
              }
          },
          'content2@': {
              templateUrl: 'shows.html',
              controller: function($scope, ShowsService) {
                $scope.shows = ShowsService.list();
              }
          }
      }
  })
  .state('app.shows.detail', {
      url: '/',
      params: {
        // this is for hiding parameter from URL
        id: null,
      },
      views: {
          'detail@app.shows': {
              templateUrl: 'show-detail.html',
              controller: function($scope, $stateParams, ShowsService) {
                  $scope.selected = ShowsService.find($stateParams.id);
                }
          }
      }

  });

Plunker 示例

http://plnkr.co/edit/Dq5sDBzREqDzlEnNVhfp?p=preview

问题

我们应该怎么做才能防止其他视图(例如,当我点击content1 标题时content2)同时发生变化? 同样在生产中我们会有很多视图,不只是这两个,为了简洁起见,我们简化了示例。

现在我们不确定我们是否遗漏了文档中的某些内容或概念有误,并且我们想滥用 ui 路由器来实现它不是为它设计的东西。

(我们知道但没有回答在同一屏幕上加载相同组件的多个视图的问题的类似问题: angular ui router state - multiple states with same template and controller)

【问题讨论】:

  • 你期望它做的代码没有做什么?你问题的那部分没有明确定义。据我推测,您正在尝试对通过路由管理的特定指令进行 ng-repeat?
  • 我编辑了这个问题。我希望现在很清楚。简而言之:content1 的更改不应更改 content2。现在这就是它的工作原理。

标签: javascript angularjs angular-ui-router


【解决方案1】:

没有看到 ShowsService.list(); 的样子,很难诊断。

我的猜测是`ShowsService 注册为工厂而不是服务。看到这个答案https://stackoverflow.com/a/15666049/1202630

module.service(‘ShowsService’, function(){
    // Your Stuff
});

【讨论】:

  • 您无需猜测。它位于plunker 示例中,script.js 来自line 69。是的,它注册为factory
猜你喜欢
  • 2015-01-28
  • 1970-01-01
  • 2018-01-07
  • 2015-10-06
  • 2015-10-16
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
相关资源
最近更新 更多