【发布时间】:2015-11-09 04:20:21
【问题描述】:
考虑 angularjs 中的自定义指令:
.directive('myDir', function() {
return {
restrict: 'E',
template: "..."
}
})
据我所知,标签<my-dir></myDir> 没有关联的默认样式(或者,至少,它不是块标签)。现在我想设置它的样式并将其放置在页面的正确位置。我有 2 个选择:
1) 使用此模板:
.directive('myDir', function() {
return {
restrict: 'E',
template: "<div class="layout">...</div>",
}
})
还有css:
.layout {
/* bla bla bla */
}
但这在 DOM 3 中引入了一个新的不必要的级别,因为如果我写了类似 <my-dir class="layout"></my-dir> 的内容并附加了正确的 css,它无论如何都会起作用,但我必须记住每次添加相同的 css 类在我的代码中使用<my-dir>(这不是DRY)。
2) 这导致我在 post-link 函数中添加样式:
.directive('myDir', function() {
return {
restrict: 'E',
template: "...",
link: function(scope, element, attrs) {
element.addClass('layout');
}
}
})
哪种策略更好?有我看不到的优点或缺点吗?
更新:
在指令定义中使用replace: true 不是一种选择,因为它已被弃用,并且在使用引导程序时,<my-dir class="visible-xs"></my-dir> 之类的东西可能很有用。
【问题讨论】:
标签: javascript html css angularjs