我正在处理可以通过单击标题栏进行展开/折叠的表格。为了实现这一点,我有两个指令作为兄弟姐妹出现在标记中:slideToggle和slideable。我想共享一个包含两个指令之间的打开/关闭状态的变量。我已经创建了一个父指令slideContainer作为API,因为根据我的理解,兄弟指令不能自己共享一个控制器实例。我希望通过向slideContainer元素添加属性来在标记中设置状态。该变量应该被访问,保持最新,并且可以从所有三个指令中变化,并且DOM应该可以访问双向绑定,因为视图的一部分将取决于状态。起初我以为我会在这里发帖以了解最好的"实现这一目标的方法,但我已经尝试了许多方法,并且无法使其发挥作用。我现在在这里:
slideable.coffee:
directives.directive "slideContainer", () ->
link: (scope, element, attrs) ->
scope.closed = "closed" in attrs
controller: ($scope) ->
this.closed = $scope.closed
directives.directive "slideToggle", () ->
scope: {}
require: "^slideContainer"
link: (scope, element, attrs, slideContainerCtrl) ->
scope.closed = slideContainerCtrl.closed
target = null
content = null
element.bind "click", () ->
target = document.querySelector(attrs.slideToggle) if (!target)
content = target.querySelector(".slideable_content") if (!content)
if slideContainerCtrl.closed
target.style.maxHeight = content.clientHeight + "px"
else
target.style.maxHeight = "0px"
slideContainerCtrl.closed = !slideContainerCtrl.closed
directives.directive "slideable", () ->
scope: {}
restrict: "C"
require: "^slideContainer"
compile: (element, attr) ->
contents = element.html()
element.html("<div class='slideable_content'>#{contents}</div>")
(scope, element, attrs, slideContainerCtrl) ->
transProp = attrs.transProp || "max-height"
transTimeFunc = attrs.transTimeFun || "linear"
transDur = attrs.transDur || "0.5s"
maxHeight = if slideContainerCtrl.closed "0" else "1000px"
element.css({
"overflow": "hidden",
"max-height": maxHeight,
"transition": "#{transProp} #{transTimeFunc} #{transDur}",
"width": "100%"
})
table.html:
<div slideContainer closed>
<!-- initial state determined by presence of closed attr above -->
<div slideToggle>
<img ng-if="closed" src="closed.jpg">
<img ng-if="!closed" src="open.jpg">
<!-- TABLE TITLE -->
</div>
<table class="=open-ended-in-process-table slideable">
<thead>
<tr>
<!-- COLUMN TITLES -->
</tr>
</thead>
<tbody>
<tr ng-repeat="thing in list">
<!-- TABLE DATA -->
</tr>
</tbody>
</table>
</div>