More than one template in same component in AngularJS 1.5

后端 未结 2 582
傲寒
傲寒 2020-12-09 19:12

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.

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 19:58

    I use two ways for making dynamic template of a component in 1.5.x:

    1) Pass via attr property:

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

    2) Inject a service into template and get template from there:

    templateURL function:

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

    In getTemplate function return template url based on variable

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

    Pass variable 'view' to factory firstly via a set method.

    If you need more change in html template, back to use directive and use compile service with more support.

提交回复
热议问题