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

问题描述

我见过很多与此非常相似的问题,但我是 Angular 的新手,所以它们完全没有意义.这是我的情况:

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>

如何在 template 定义中处理这些?我一直在阅读有关我需要重写的 $compile() 函数的信息,但还不清楚如何执行此操作.模板只是简单的字符串,所以我觉得我可以将它们内联而不是将它们作为单独的文件进行引用.

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中是edit-button;有一个从连字符到驼峰式大小写的内置转换,如果你不知道它会咬你.

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>

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

10-29 15:04