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

wmn*_*tin 11 angularjs angularjs-components

我可以在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")
    }      
}
})
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 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];
    }
});
Run Code Online (Sandbox Code Playgroud)

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

<test-component template='first'></test-component>
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于在<test-component>标记内使用template = attribute的"硬编码"值.由于你需要像<test-component template ='{{templateName}}'> </ test-component>这样的解决方案,因为没有内插值,这个解决方案不起作用 (6认同)

Vu *_*yet 9

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

1)通过attr属性:

templateUrl: function($element, $attrs) {
      return $attrs.template;
}
Run Code Online (Sandbox Code Playgroud)

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

templateURL函数:

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

在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";       
}
Run Code Online (Sandbox Code Playgroud)

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

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