如何填充AngularJS嵌套的类别下拉列表



在我的后端,我有一个嵌套的类别结构,像这样:

Category
--------
id
parent_id
name

我把它作为一个单维数组完全加载到$scope.categories

在屏幕上,我想在每个级别上显示一个下拉菜单,显示相应的路径。例如,如果路径是cars/sedan/ford/taurus,我想显示四个下拉菜单:

汽车v 轿车v 福特v 金牛座v

当一个下拉菜单被更改时,右边的下拉菜单应该被删除,而最右边的下拉菜单则填充所有子类,其父类是我刚刚选择的那个。常规的东西。

我还创建了一个category_path数组,其中包含产品类别路径中的每个category_id: [null, category_id, category_id, category_id]

然后我做了这个:

<select
    ng-repeat="item in category_path"
    ng-model="selected_category[$index]"
    ng-options="category.name for category in (categories | filter : { parent_id: item } : true ) track by category.id "
    ng-change="select_category(selected_category[$index], $index)"
    ></select>

在我的控制器上:

$scope.select_category = function ( selected_category, index ) {
    if ( $filter('filter') ($scope.categories, { parent_id: selected_category.id }, true).length ) {
        if ( $scope.category_path[index+1] != undefined ) {
            $scope.category_path = $scope.category_path.slice(0, index+1);
            $scope.category_path[index+1] = selected_category.id;
        } else {
            $scope.category_path.push( selected_category.id );
        }
    } else {
        $scope.product.category_id = selected_category.id;
    }
}

这就像魅力一样,除了我不能根据当前产品category_path数组填充每个下拉列表的默认值。

我试着:

ng-init="select_category[$index] = category_path[$index]"

没有成功。想法吗?

您的category_path数组持有不同于模型的值,即selected_category数组。后者似乎保存JSON字符串,而前者保存单个值(用于id键)。

要使默认值工作,请将完整的JSON对象插入模型数组。

最新更新