AngularJS 1.5 中同一组件中的多个模板 [英] More than one template in same component in AngularJS 1.5

查看:27
本文介绍了AngularJS 1.5 中同一组件中的多个模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 AngularJS 1.5 组件中使用多个模板吗?我有一个具有一个属性的组件,因此我想根据该属性名称加载不同的模板.如何实现基于元素属性名的模板加载?

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

谢谢.

推荐答案

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

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

1) 通过 attr 属性传递:

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

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

templateURL 函数:

templateURL function:

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

在getTemplate函数中根据变量返回模板url

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

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

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

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

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

这篇关于AngularJS 1.5 中同一组件中的多个模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆