将optgroups添加到角度 - 以异步方式选择

时间:2016-08-21 08:11:48

标签: angularjs asynchronous selectize.js

我在我的项目中使用angular-selectize指令。为此,我需要异步加载optgroups。到目前为止,我尝试了多种方法,但没有一种方法可行。问题是,您无法同步使用promise返回的数据。另一方面,我也无法在promise回调中初始化selectize。以下是我目前拥有的代码。请注意,它仅用于了解我正在玩的数据,而不是将其作为您可以正确考虑的内容呈现。

app.js

$http
.get('/get-categories')
.then(getCategoriesSCB, getCategoriesFCB);
function getCategoriesSCB(response) {
  if(typeof(response.data) === 'object') {
    posControl.menuCategories = response.data[0];
    posControl.menuCategoryGroups = response.data[1];
  }
  else {
    getCategoriesFCB(response);
  }
}
function getCategoriesFCB(response) {
  console.log(response);
}

posControl.menuConfig = {
  valueField: 'id',
  labelField: 'title',
  placeholder: 'Select Category',
  optgroupField: 'class',
  optgroupLabelField: 'label',
  optgroupValueField: 'value',
  optgroups: posControl.menuCategoryGroups,
  maxItems: 1,
  searchField: ['title', 'category'],
  onInitialize: function(selectize) {
    console.log('selectize is here');
  },
}

的index.html

<selectize config="POSCtrl.menuConfig" options="POSCtrl.menuCategories" ng-model="POSCtrl.menuModel"></selectize>

ajax调用返回的数据

[
    // this array has to be used for options.
    [{
        "class": "57b83830babb9",
        "category": "Food Menu",
        "id": "57b83855b23f9",
        "title": "Beverages"
    }, {
        "class": "57b83830babb9",
        "category": "Food Menu",
        "id": "57b83855c05de",
        "title": "Cuisines"
    }, {
        "class": "57b83830babb9",
        "category": "Food Menu",
        "id": "57b83855cdcb4",
        "title": "Steaks"
    }, {
        "class": "57b83830d0899",
        "category": "Wholesale Coffee",
        "id": "57b83830d0899",
        "title": "Wholesale Coffee"
    }],
    // this array has to be used for optgroups
    [{
        "value": "57b83830babb9",
        "label": "Food Menu"
    }, {
        "value": "57b83830d0899",
        "label": "Wholesale Coffee"
    }]
]

1 个答案:

答案 0 :(得分:0)

您应该能够通过直接在posControl.menuConfig上设置值来异步加载选择:

function getCategoriesSCB(response) {
  if (typeof(response.data) === 'object') {
    posControl.menuConfig.options = response.data[0];
    posControl.menuConfig.optgroups = response.data[1];
  }
}