如何在角度1.5中为相同的组件使用不同的模板URL

时间:2016-11-10 13:53:20

标签: angularjs components reusability angular-components

我已按照以下方式实施了一个组件

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?如果是的话,应该怎么做?

1 个答案:

答案 0 :(得分:0)

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

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

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