Angular ui-router基于路径参数呈现不同的组件

时间:2016-08-12 14:43:47

标签: javascript angularjs angular-ui-router angularjs-routing angular-components

使用Angular UI路由器,我尝试根据$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

有没有办法简化这个?或者为此可能有一个特定的功能?

2 个答案:

答案 0 :(得分:1)

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

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

其他方式是您可以为每个chapter&amp;有一些URL约定。之后,您可以使用templateUrl component函数或ng-include指令src来渲染这些模板。

答案 1 :(得分: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;
相关问题