AngularJS 1.5中同一组件中的多个模板

问题描述 投票:11回答:2

我可以在AngularJS 1.5组件中使用多个模板吗?我有一个组件有一个属性,所以我想根据该属性名称加载不同的模板。如何根据元素的属性名称加载模板?

jsConfigApp.component('show', {
templateUrl: 'component/show.html',  //How to change it based on attribute value?
bindings:{
    view:"@"
},
controller: function () {
    console.log(this.view)
    if (this.view = "user") {
       console.log("user")
    } else if (this.view = "user") {
        console.log("shop")
    } else {
        console.log("none")
    }      
}
})

谢谢。

angularjs angularjs-components
2个回答
9
投票

我使用两种方法在1.5.x中制作组件的动态模板:

1)通过attr属性:

templateUrl: function($element, $attrs) {
      return $attrs.template;
}

2)将服务注入模板并从那里获取模板:

templateURL函数:

templateUrl: function($element, $attrs,TemplateService) {
      console.log('get template from service:' + TemplateService.getTemplate());
      return TemplateService.getTemplate();
}

在getTemplate函数中,返回基于变量的模板url

getTemplate: function(){
     if (this.view = "user") {
          return "user.html";
    } else if (this.view = "user") {
          return "shop.html";
    } else {
        console.log("none")
    } 
    return "shop.html";       
}

首先通过set方法将变量'view'传递给factory。

如果您需要在html模板中进行更多更改,请返回使用指令并使用更多支持的编译服务。


22
投票

将模板作为参数传递给组件怎么样?例如,创建一个组件,如:

module.component('testComponent', {
    controllerAs: 'vm',
    controller: Controller,
    bindings: {
        template  : '@'
    },
    templateUrl: function($element, $attrs) {
        var templates = {
            'first' :'components/first-template.html',
            'second':'components/second-template.html',
            'third' :'components/third-template.html'
        }
        return templates[$attrs.template];
    }
});

使用以下组件可能会有所帮助

<test-component template='first'></test-component>
© www.soinside.com 2019 - 2024. All rights reserved.