Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formly Default value in dynamic options

I use angular js formly to create my web forms. my problem is when is use select with dynamic options the defaultValue property dos not work. but when is set static data to options it is work. how can i set default value (selected option) in formly when i get options from remote server ?

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

}

like image 629
Mohammad Zafari Avatar asked Nov 26 '25 04:11

Mohammad Zafari


1 Answers

You can use controller option for this field.

This is example for getting all categories for selection options and setting value of select field dynamically according to current product's category:

  {
    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;
      });
    }
  }

And in your case it should be something like this:

{
  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 
    };
  }
}
like image 145
Victor Borshchov Avatar answered Nov 28 '25 20:11

Victor Borshchov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!