More than one template in same component in AngularJS 1.5

wmnitin picture wmnitin · Jun 19, 2016 · Viewed 8k times · Source

Can I use more than one template in AngularJS 1.5 components ? I have one component having one attribute, so I want to load different template based on that attribute name. How can I achieve loading of templates based on attribute name of element?

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")
    }      
}
})

Thanks.

Answer

ozhanli picture ozhanli · Jan 19, 2017

What about passing template as an parameter to component? For example create a component like:

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];
    }
});

And using component as below may help

<test-component template='first'></test-component>