基于属性的指令中的动态模板?

时间:2013-06-25 00:12:47

标签: angularjs angularjs-directive

我见过很多与此类似的问题,但我是Angular的新手,所以他们并非相当有意义。这是我的坐标:

我有一个定义的指令:

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

我像这样使用这个指令:

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

理想情况下,我想在此添加可选属性,例如:

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

如何在template定义中处理这些问题?我一直在阅读我需要覆盖的$compile()函数,但还没有明确如何这样做。模板只是简单的字符串,所以我觉得我可以将它们内联到它们而不是将它们作为单独的文件引用。

谢谢!

1 个答案:

答案 0 :(得分:3)

通过将它们添加到范围语句中,使它们在指令中可访问,就像拥有标题一样。然后将按钮添加到模板中,并按条件对它们进行条件化:

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>

请注意,它是HTML中指令和编辑按钮中的editButton;有一个从连字符到驼峰的内置转换,如果你不知道它会咬你。

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

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>
相关问题