您可以創建兩個指令,它們之間有父/子關係。
看看我創建的手風琴指令,我相信這是你需要的,以便弄清楚你的情況。
指令:
app.directive("accordion", function() {
return {
template: "<div ng-transclude></div>",
restrict: "E",
scope: {
closeall: "@"
},
transclude: true,
replace: true,
controller: function ($scope, $element, $attrs) {
var itensScope = [];
var addItemScope = function (scope) {
itensScope.push(scope);
};
var closeItens = function() {
if ($scope.closeall == "false") return;
angular.forEach(itensScope, function (scope) {
scope.showItem = false;
});
}
return {
addItemScope: addItemScope,
closeItens: closeItens
};
}
};
});
app.directive("accordionItem", function() {
return {
template: "<div><div class='item' ng-class='{itemClose: !showItem}'>{{title}}</div><div class='itemInformation' ng-show='showItem' ng-transclude></div></div>",
restrict: "E",
transclude: true,
replace: true,
scope: {
title: "@"
},
require: "^accordion",
link: function (scope, element, attrs, ctrl, transcludeFn) {
ctrl.addItemScope(scope);
element.bind("click", function() {
ctrl.closeItens();
scope.$apply(function() {
scope.showItem = !scope.showItem;
});
});
}
};
});
用法:
<accordion closeall="true">
<accordion-item title="A">
<p>
A
</p>
</accordion-item>
<accordion-item title="B">
<p>
B
</p>
</accordion-item>
</accordion>
我創造了這個例子一段時間了,它在我的GitHub上可用:https://github.com/rodrigobranas/branas-angular-ui
您使用'ng-click'。 – Casey
@Casey嗯,但我會如何檢測元素點擊收縮?點擊時需要展開我的列表,但在用戶點擊其他元素時收縮我的列表。 ng-click似乎只能在元素點擊時檢測到。 – testing
爲什麼需要在每個文檔點擊時運行'$ scope.apply()'? – charlietfl