在指令动态模板基于属性? [英] Dynamic template in directive based on attributes?

查看:99
本文介绍了在指令动态模板基于属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看见的Ive一堆类似这样的问题pretty,但我新的角度,使他们没有的非常的决策意识。这里是我的sitaution:

Ive seen a bunch of questions pretty similar to this, but I'm new to Angular so they aren't quite making sense. Here's my sitaution:

我有一个指令定义的:

robus.directive("titlebar", function() {
  return {
    restrict: "E",
    scope: { title: '@title' },
    template: "<header class='bar-title'><h1 class='title'>{{title}}</h1></header>",
    replace: true
  }
});

我使用这个指令像这样:

I use this directive like this:

<titlebar title="{{workout.name}}"></titlebar>

在理想情况下,我想可选属性添加到这个,如:

Ideally, I want to add optional attributes into this, like:

<titlebar title="{{workout.name}}" editButton="true" closeButton="true"></titlebar>

我要如何处理这些在模板定义?我一直在阅读关于 $编译()函数,我需要重写,但尚未就如何做到这一点清楚。模板只是简单的字符串,所以我觉得我可以做他们的内联与引用它们作为单独的文件。

How do I handle these in the template definition? I've been reading about a $compile() function that I need to override, but haven't been clear on how to do so. The templates are just simple strings, so I feel like I can just do them inline versus referencing them as separate files.

谢谢!

推荐答案

请他们的指令中访问将它们添加到范围说明书,就像你拥有的称号。然后将按钮添加到模板,条件化他们像这样:

Make them accessible within the directive by adding them to the scope statement, just as you have the title. Then add the buttons to the template, and conditionalize them like so:

robus.directive("titlebar", function() {
  return {
    restrict: "E",
      scope: { title: '@title', edit: '@editButton', cancel: '@cancelButton' },
      template: "<header class='bar-title'><h1 class='title'>{{title}}</h1><span ng-show='edit'>Edit</span><span ng-show='cancel'>Cancel</span></header>",
    replace: true
  }
});

<titlebar title="{{workout.name}}" edit-button="true" cancel-button="false"></titlebar>

请注意,它是editButton在HTML指令和编辑键;有一个从复姓到骆驼情况下,内置的转换,如果你不知道它会咬你的。

Note that it's editButton in the directive and edit-button in the HTML; there's a built-in conversion from hyphenated to camel-case that will bite you if you're not aware of it.

另外,我建议使用transclude这里,因为我认为它会读一点更干净:

Also, I recommend the use of transclude here, as I think it will read a bit more cleanly:

robus.directive("titlebar", function() {
  return {
    restrict: "E",
      scope: { edit: '@editButton', cancel: '@cancelButton' },
      template: "<header class='bar-title'><h1 class='title' ng-transclude></h1><span ng-show='edit'>Edit</span><span ng-show='cancel'>Cancel</span></header>",
    transclude: true,
      replace: true
  }
});

<titlebar edit-button="true" cancel-button="false">{{workout.name}}</titlebar>

这篇关于在指令动态模板基于属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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