从ui-select的json树视图

时间:2015-10-02 15:50:25

标签: json angularjs ui-select

希望在ui-select的树视图结构中显示嵌套的json 我可以使用angular指令创建一个树:

代码

data:        
$scope.treeFamily = {
            name : "Parent",
            children: [{
                name : "Child1",
                children: [{
                    name : "Grandchild1",
                    children: []
                },{
                    name : "Grandchild2",
                    children: []
                },{
                    name : "Grandchild3",
                    children: []
                }]
            }, {
                name: "Child2",
                children: []
            }]
        };


directive:
        module.directive("tree", function($compile) {
            return {
                restrict: "E",
                transclude: true,
                scope: {family: '='},
                template:       
                    '<ul>' + 
                        '<li ng-transclude></li>' +
                        '<p>{{ family.name }}</p>' + 
                        '<li ng-repeat="child in family.children">' +
                            '<tree family="child"></tree>' +
                        '</li>' +
                    '</ul>',
                compile: function(tElement, tAttr, transclude) {
                    var contents = tElement.contents().remove();
                    var compiledContents;
                    return function(scope, iElement, iAttr) {
                        if(!compiledContents) {
                            compiledContents = $compile(contents, transclude);
                        }
                        compiledContents(scope, function(clone, scope) {
                                 iElement.append(clone); 
                        });
                    };
                }
            };
        });

html:
        <tree family="treeFamily">

        </tree>

我希望能够在ui-select中搜索/选择每个节点。寻找建议。

1 个答案:

答案 0 :(得分:3)

可悲的是,实际上没有任何方法可以使你的指令在ui-select指令内部工作,因为它正在使用重复处理它的所有选项创建,并且没有提供覆盖它的选项重写ui选择框。但是,您可以模板显示项目。首先将数据展平为数组:

 [{name: 'Parent', treelevel: 0},
  {name: 'Child', treelevel: 1},
  {name: 'Grandchild', treelevel: 2}]

然后从那里写下你的ui-select如下:

<ui-select ng-model="person.selected" theme="select2" ng-disabled="disabled" style="min-width: 300px;">
  <ui-select-match placeholder="Select a person in the list or search his name/age...">{{$select.selected.name}}</ui-select-match>
  <ui-select-choices repeat="person in people | propsFilter: {name: $select.search, age: $select.search}">
    <div style="padding-left: {{15 * person.treelevel}}px" ng-bind-html="person.name | highlight: $select.search"></div>
  </ui-select-choices>
</ui-select>

将以树格式显示所有内容。以下plunk的工作版本为:http://plnkr.co/edit/Rzlu6zIHOYzVlhQebh7V?p=preview