2013-06-25 49 views
3

我见过一堆与此非常相似的问题,但我是Angular的新手,所以他们不是,相当有意义。这里是我的sitaution:基于属性的指令中的动态模板?

我定义的指令:

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()函数,但尚未明确如何这样做。模板只是简单的字符串,所以我觉得我可以将它们内联,而将它们作为单独的文件引用。

谢谢!

回答

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> 

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

另外,我建议使用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> 
+0

啊,那太好了。有意义的是,你可以在模板中使用'ng-show' - 甚至没有想到要使用它们! – dmackerman