【问题标题】:Angularjs - How to loop through a list of dictionaries in select optgroup?Angularjs - 如何遍历选择 optgroup 中的字典列表?
【发布时间】:2019-06-03 12:10:30
【问题描述】:

我有一个类别列表,每个类别下都包含一个子类别。我正在尝试在选择选项 optgroup 中获取它们,列表如下所示:

{
  "data": [
    {
      "category": "First Category", 
      "0": {
        "name": "Sub 1", 
        "under": [
          "Under 1", 
          "Under 2"
        ]
      }, 
      "1": {
        "name": "Sub 2", 
        "under": [
          "Under 1", 
          "Under 2", 
          "Under 3"
        ]
      }, 
      "2": {
        "name": "Sub 3", 
        "under": [
          "Under 1", 
          "Under 2"
        ]
      }
    },
    {
      "category": "Second Category", 
      "0": {
        "name": "Sub 1", 
        "under": [
          "Under 1", 
          "Under 2"
        ]
      }, 
    },
  ]
}

我有另一个包含所有类别的选择。第二个显示取决于我的第一个选择,因此,例如,如果我选择 First Category,则所有 subs 和 sub 应附加在第二个选择中:

// Fetch all available categories
$scope.initCategories = function(obj){
    $scope.promise = sendRequest.sendObject('/fetch-categories', obj, config)
    $scope.promise.then(function(success) {
        $scope.categories = success.data
        $scope.stepData.category = $scope.categories
        return true
    }, function(err) {
        return false, err
    })
}

<select class="form-control custom-select" name="categories" ng-model="stepData.category" ng-options="x.category for x in categories track by x.category">
</select>

<select ng-if="stepData.category" class="form-control custom-select" ng-model="stepData.sub" ng-options="sub group by sub.name for (index, key) in stepData.category[index]"></select>

这是我正在尝试做的一个示例:http://jsfiddle.net/rtCP3/182/

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    我得到了它的工作,我在第二个选择中使用了ng-repeat 而不是ng-options

    <select ng-if="category" id="product_sub_category" name="product_sub_category" class="form-control custom-select" ng-model="sub_category" ng-change="setSubCategory()">
        <optgroup ng-repeat="(index, key) in category track by $index" label="<%key.name%>">
            <option ng-repeat="value in key.under track by $index">
                <%value%>
            </option>
        </optgroup>
    </select>
    

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 2012-07-07
      • 2023-03-14
      • 2020-05-16
      • 2012-07-04
      • 2019-11-29
      相关资源
      最近更新 更多