angularjs – Angular-ui-select父子组

我有一个充满父对象的数组,并嵌套在每个父对象中我有一个带有子对象的数组.在没有重建我的模型的情况下,我很难找到使用angular-ui-select的最佳方法来实现一个启用了分组的​​下拉选择框.

$scope.allCategories = [
        {
            "code": "AAAA",
            "name": "animals",
            "categories": [
                {
                    "code": "APET",
                    "name": "pets"
                },
                {
                    "code": "ASUP",
                    "name": "supplies"
                },
                {
                    "code": "AOTH",
                    "name": "other"
                }
            ]
        },
        {
            "code": "CCCC",
            "name": "community",
            "categories": [
                {
                    "code": "CCNW",
                    "name": "classes and workshops"
                },
                {
                    "code": "COMM",
                    "name": "events"
                },
                {
                    "code": "CGRP",
                    "name": "groups"
                }
            ]
        }
    ]

这是我到目前为止所构建的内容,但是我需要使用angular-ui-select的许多功能而不需要重新发明轮子.

<select class="form-control">
    <optgroup ng-repeat="category in allCategories" label="{{category.name}}">
        <option ng-repeat="childCategory in category.categories" value="{{childCategory.code}}">{{childCategory.name}}</option>
    </optgroup>
</select>

最佳答案 我认为您需要将层次结构展平为数组.

像:http://plnkr.co/edit/ESHmxOqMuIvAYFdNYcV0

这是我为你的例子写的扁平化函数.这些属性可以很容易地适应其他用例:

function flattenCategories(categories, depth, parent){
  if(angular.isUndefined(depth)){ depth = 1; }
  var flat = [];
  angular.forEach(categories, function(category){
    flat.push({
                code: category.code,
                name: category.name,
                depth: depth,
                parent: parent
              });
    if(category.categories){
      var childCategories = flattenCategories(category.categories, depth+1, (angular.isDefined(parent)?parent+'.':'')+category.code);
      if(childCategories.length){
        flat.push.apply(flat, childCategories);
      }
    }
  });
  return flat;
}

$scope.flatCategories = flattenCategories( $scope.allCategories );

使用类中的depth属性(即.class =“depth – {{category.depth}}”),您可以创建缩进和组头样式.您需要为需要支持的许多深度生成CSS.

点赞