动态选项中的默认值

formly Default value in dynamic options

本文关键字:默认值 选项 动态      更新时间:2023-09-26

我通常使用角度js来创建我的Web表单。我的问题是当使用带有动态选项的选择时,默认值属性不起作用。但是当将静态数据设置为选项时,它是有效的。当我从远程服务器获取选项时,如何在 formly 中设置默认值(选定的选项)?

{
className: 'col-sm-3',
key: 'cityId',
type: 'select',
templateOptions: {
    placeholder: 'City',
    required: true,
    label: 'City',
    valueProp: 'id',
    labelProp: 'name',
    options: $scope.cityCombo
},
defaultValue: '3209C692-B8D4-4AB0-9F40-008A7C4644F9',

}

您可以为此字段使用controller选项。

这是获取选择选项的所有类别并根据当前产品的类别动态设置选择字段值的示例:

  {
    key: 'category',
    type: 'select',
    wrapper: "loading",
    templateOptions: {
      label: 'Category',
      options: [],
      valueProp: 'name',
      labelProp: 'name'
    },
    controller: function($scope, productsFactory, $routeParams) {
      $scope.to.loading = productsFactory.getCategories().then(function(response){
        $scope.to.options = response.data.categories;
        // note, the line above is shorthand for:
        // $scope.options.templateOptions.options = data;
        productsFactory.getProduct($routeParams.id).then(function(response) {
          $scope.model.category = response.data.product.category.name;
        });
        return response;
      });
    }
  }

在您的情况下,它应该是这样的:

{
  className: 'col-sm-3',
  key: 'cityId',
  type: 'select',
  templateOptions: {
    placeholder: 'City',
    required: true,
    label: 'City',
    valueProp: 'id',
    labelProp: 'name',
    options: $scope.cityCombo
  },
  // defaultValue: '',
  controller: function($scope /*inject*/) {
    // some code 
    $scope.model.cityId = cityId; // dynamically set cityId
    // some code 
    };
  }
}