我正在尝试编写一个AngularJs指令,它将以类似结构的树递归地嵌套UI Bootstrap手风琴。
我一直在尝试应用此处找到的食谱: Recursion in Angular directives,特别是this one ...
我取得了一些成功......有一些我无法弄清楚的问题。
这是我的result。
有一个明显的问题,我的标题只显示“叶子”项目。
为了在手风琴组中添加子元素,我使用了
$element.find("p").replaceWith(childItem);
但我认为必须有更优雅的方式。
答案 0 :(得分:2)
我根据Reference question中的另一个例子开始工作(是的,应该深入挖掘......)
答案 1 :(得分:0)
这是保留的Plunker,具有粗略但有效的增强功能,可以将指令中的子元素和标题字段的名称与深度分开(参见“kids”和“childs”$ scope变量),因此该指令可以用于任何数据集。
function Node(name, children) {
this.name = name;
this.children = children || [];
}
angular.module('myApp', ['ui.bootstrap'])
.directive('nodeList', function($compile) {
return {
restrict: 'E',
terminal: true,
scope: {
nodes: '=ngModel',
kids: '@',
headingField: '@'
},
link: function ($scope, $element, $attrs) {
if (angular.isArray($scope.nodes)) {
$element.append('<accordion close-others="true"><node ng-repeat="item in nodes" ng-model="item" childs="{{kids}}" heading-field="{{headingField}}"></node></accordion>');
}
$compile($element.contents())($scope.$new());
}
};
})
.directive('node', function($compile) {
return {
restrict: 'E',
terminal: true,
scope: {
node: '=ngModel',
childs: '@',
headingField: '@'
},
link: function ($scope, $element, $attrs) {
if (angular.isArray($scope.node[$scope.childs]) && $scope.node[$scope.childs].length > 0) {
$element.append('<accordion-group><accordion-heading>{{node[headingField]}}</accordion-heading><node-list ng-model="node[childs]" kids="{{childs}}" heading-field="{{headingField}}"></node-list></accordion-group>');
} else {
$element.append('<accordion-group><accordion-heading>{{node[headingField]}}</accordion-heading></accordion-group>');
}
$compile($element.contents())($scope.$new());
}
};
})
.controller('myView', function($scope) {
$scope.data = [
new Node('Group 1', [
new Node('Sub 1.1', [
new Node('Sub 1.1.1', [
new Node('Child 1.1.1.1'),
new Node('Child 1.1.1.2')]),
new Node('Sub 1.1.2', [
new Node('Child 1.1.2.1'),
new Node('Child 1.1.2.2'),
new Node('Child 1.1.2.3')])]),
new Node('Sub 1.2', [
new Node('Child 1.2.1'),
new Node('Child 1.2.2')])]),
new Node('Group 2', [
new Node('Sub 2.1', [
new Node('Child 2.1.1')])])];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="myView">
<h1>Test</h1>
<node-list ng-model="data" kids="children" heading-field="name"></node-list>
</div>
</body>
</html>
答案 2 :(得分:0)
适用于较新版本的UI Bootstrap
我还不能发表评论,但我想补充一点,来自@ user280767的plunkr适用于他们正在使用的ui.bootstrap版本。对我来说,我不得不用他们文档中列出的新格式uib-accordion *替换指令中的accordion *元素。希望这有助于用户!