Angular ui路由器根据路由参数呈现不同的组件

Angular ui-router render different component based on route params

本文关键字:组件 参数 路由器 ui 路由 Angular      更新时间:2023-09-26

使用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

有什么方法可以简化这一点吗?或者可能有一个特定的功能用于此目的?

如果不向组件传递任何数据,我认为您可以执行如下操作。

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

另一种方法是,您可以为每个chapter&有一些URL约定。之后,您可以使用componenttemplateUrl函数或srcng-include指令来呈现这些模板。

正如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;