如何在 Angular 1.5 中为同一组件使用不同的模板 url

Posted

技术标签:

【中文标题】如何在 Angular 1.5 中为同一组件使用不同的模板 url【英文标题】:How do I use different template urls for same component in angular 1.5 【发布时间】:2017-03-24 13:56:47 【问题描述】:

我已经通过以下方式实现了一个组件

angular.module('moduleName')
        .component('myComponent', 
            templateUrl: 'templatePath1.tpl.html',
            controller: myController,
            controllerAs: 'vm',
            bindings: 
                b1: '&',
                b2: '&'
            
        );

我将其用作<my-component b1="someThing1" b2="someThing2"></my-component>

现在,我想将相同的 myController 与位于 templatePath2.tpl.html 的另一个模板一起使用。

一种方法是创建另一个组件myComponent2

angular.module('moduleName')
        .component('myComponent2', 
            templateUrl: 'templatePath2.tpl.html',
            controller: myController,
            controllerAs: 'vm',
            bindings: 
                b1: '&',
                b2: '&'
            
        );

有什么方法可以使用以前的组件并根据 attr 选择 templateUrl?如果是,应该怎么做?

【问题讨论】:

您在使用相同的模板 url 和控制器创建 mycomponent2 时遇到错误吗? 【参考方案1】:

templateUrl 可以是一个函数,它获取元素和属性作为参数:

angular.module('moduleName')
    .component('myComponent', 
        templateUrl: function(element, attrs) 
                      return 'templatePath' + attrs.x + '.tpl.html';
                     ,

<my-component x="1"></my-component>

【讨论】:

以上是关于如何在 Angular 1.5 中为同一组件使用不同的模板 url的主要内容,如果未能解决你的问题,请参考以下文章