【问题标题】:How do I use different template urls for same component in angular 1.5如何在 Angular 1.5 中为同一组件使用不同的模板 url
【发布时间】: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 时遇到错误吗?

标签: angularjs components reusability angular-components


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-10-20
    • 2017-10-27
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2018-05-16
    • 2021-03-18
    相关资源
    最近更新 更多