有没有办法为 angular 1.5 组件动态呈现不同的模板 [英] Is there a way to dynamically render different templates for an angular 1.5 component

查看:27
本文介绍了有没有办法为 angular 1.5 组件动态呈现不同的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a number of angular 1.5 components that all take the same attributes and data structure. I think they could be re-factored into a single component, but I need a way to dynamically choose a template based upon the interpolated value of the type attribute.

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 中的值是未插值的所以我不会得到传入数据中指定的类型.

I can't use the templateUrl function($element, $attrs) {} because the values in the $attrs are uninterpolated so I wouldn't get the type specified in the passed in data.

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

I could just have one big template with a series of ng-if or ng-switch directives, but I would like to keep the templates separate.

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

Alternatively, I could just keep the components separate and use ng-switch etc in the parent component, but I don't like this as it seems like a lot of repetition.

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

I'm looking for a solution where I can use the interpolated type passed into the bindings to match a template url for each type which will then be used to build the component.

这可能吗?

谢谢

推荐答案

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

This is not something that components were specially made for. The task narrows down to using a directive with dynamic templates. The existing one is ng-include.

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

To use it within a component, it should be:

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';
      }
    }
  }
}

这篇关于有没有办法为 angular 1.5 组件动态呈现不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆