12

我可以在 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")
    }      
}
})

谢谢。

4

2 回答 2

24

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

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>
于 2017-01-19T13:49:58.477 回答
9

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

1) 通过 attr 属性传递:

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

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

模板网址功能:

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”传递给工厂。

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

于 2016-06-19T02:12:52.840 回答