16

我有许多 Angular 1.5 组件,它们都采用相同的属性和数据结构。我认为它们可以重新分解为单个组件,但我需要一种方法来根据type属性的插值动态选择模板。

var myComponentDef = {
    bindings: {
        type: '<'
    },
    templateUrl: // This should be dynamic based on interpolated type value
};

angular.module('myModule').component('myComponent', myComponentDef);

我不能使用 ,templateUrl function($element, $attrs) {}因为 中的值是未插值的,$attrs所以我不会得到传入数据中指定的类型。

我可以只拥有一个带有一系列ng-ifng-switch指令的大模板,但我想将模板分开。

或者,我可以将组件分开并ng-switch在父组件中使用 etc,但我不喜欢这样,因为它看起来有很多重复。

我正在寻找一种解决方案,我可以使用type传入绑定的插值来匹配每种类型的模板 url,然后将其用于构建组件。

这可能吗?

谢谢

4

3 回答 3

18

这不是专门为这些组件制造的。该任务缩小到使用带有动态模板的指令。现有的是ng-include.

要在组件中使用它,它应该是:

var myComponentDef = {
  bindings: {
    type: '<'
  },
  template: '<div ng-include="$ctrl.templateUrl">',
  controller: function () {
    this.$onChanges = (changes) => {
      if (changes.type && this.type) {
        this.templateUrl = this.type + '.html';
      }
    }
  }
}
于 2016-07-28T22:50:34.827 回答
12

您可以注入任何服务并设置动态网址

angular.module('myApp').component("dynamicTempate", {
        controller: yourController,
        templateUrl: ['$routeParams', function (routeParams) {
           
            return 'app/' + routeParams["yourParam"] + ".html";
        
        }],
        bindings: {
        },
        require: {
        }
    });

于 2017-04-14T21:54:56.793 回答
0

在任何情况下,您都必须在某处拥有切换逻辑,那么为什么不简单地将其放在父组件模板中呢?

在这种情况下,拥有干净易懂的 An​​gularJS 模板比一些重复更有价值:

<ng-container ng-switch="$ctrl.myComponentDef.type">
  <component-type1 ng-switch-when="type1" param="$ctrl.myComponentDef"></component-type1>
  <component-type2 ng-switch-when="type2" param="$ctrl.myComponentDef"></component-type2>
</ng-container>

即使您即时更改 myComponentDef.type,开关中的组件也会正确调用它们各自的$onDestroy方法$onInit并按预期加载数据 - 没有魔法,没有巫术。

于 2018-06-03T14:57:14.360 回答