formly动态选项中的默认值

时间:2016-02-03 15:53:31

标签: javascript angularjs angular-formly

我使用角度js形式来创建我的网络表单。 我的问题是什么时候使用select with dynamic options defaultValue属性dos不起作用。但是当将静态数据设置为选项时,它是可行的。 当我从远程服务器获取选项时,如何以形式设置默认值(选择的选项)?

{
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',

}

1 个答案:

答案 0 :(得分:1)

您可以对此字段使用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 
    };
  }
}