1

使用 Angular UI Router,我试图根据一个$state.params值呈现不同的组件,但我找不到一个干净的方法来做到这一点。

我已经想出了一个可行的解决方案(带有一些 ES2015 的幻想),但这远非最佳:

/* ----- chapter/chapter.controller.js ----- */
class ChapterController {

  constructor($state) {
    this.$state = $state;
    this.chapterNb = this.$state.params.chapterNb;
  }

}

ChapterController.$inject = ['$state'];

export default ChapterController;

/* ----- chapter/chapter.controller.js ----- */
import controller from './chapter.controller';

const ChapterComponent = {
  controller,
  template: `
    <chapter-01 ng-if="$ctrl.chapterNb === 1"></chapter-01>
    <chapter-02 ng-if="$ctrl.chapterNb === 2"></chapter-02>
  ` // and more chapters to come...
};

export default ChapterComponent;

/* ----- chapter/index.js ----- */
import angular from 'angular';
import uiRouter from 'angular-ui-router';

import ChaptersComponent from './chapters.component';
import ChaptersMenu from './chapters-menu';
import Chapter from './chapter';

const chapters = angular
  .module('chapters', [
    uiRouter,
    ChaptersMenu,
    Chapter
  ])
  .component('chapters', ChaptersComponent)
  .config($stateProvider => {
    'ngInject';
    $stateProvider
      .state('chapters', {
        abstract: true,
        url: '/chapters',
        component: 'chapters'
      })
      .state('chapters.menu', {
        url: '/menu',
        component: 'chaptersMenu'
      })
      .state('chapters.chapter', {
        url: '/{chapterNb:int}',
        component: 'chapter'
      });
  })
  .name;

export default chapters;

问题是每个<chapter-0*>组件都非常不同,这就是为什么它们都对应于自己的模板。我想找到一种方法来自动引用对应的章节组件,$state.params.chapterNb而不必编写那些ng-if为每个章节编写。

有没有办法简化这个?或者也许有为此目的的特定功能?

4

2 回答 2

1

如果您没有将任何数据传递给组件,我认为您可以执行以下操作。

const ChapterComponent = {
  controller,
  template: ($state) => {
     return ['<chapter-', $state.chapterNb, '></chapter-', $state.chapterNb, '>'].join("")
  }
};

另一种方法是您可以为每个模板维护单独的模板chapter并具有一些 URL 约定。此后,您可以使用 的templateUrl函数componentng-include指令来渲染这些模板src

于 2016-08-12T14:48:46.517 回答
0

正如 Pankaj Parkar 在他的回答中所建议的,在这里使用模板函数会有所帮助。

通过一些调整,我已经能够基于$state.params.

import controller from './chapter.controller';

const ChapterComponent = {
  controller,
  template: ($state) => {
    'ngInject';
    return `
      <chapter-0${$state.params.chapterNb}></chapter-0${$state.params.chapterNb}>
    `;
  }
};

export default ChapterComponent;
于 2016-08-16T08:53:19.950 回答