angular-formly

Binding Angular Formly select to a model property for its options


I am working on a legacy Angular Formly form, and I have a select formly-template field for a drop down list:

<select class="form-control" placeholder="choose ..." ng-model="model[options.key]"
        ng-options="option.value as option.name group by option.group for option in options.templateOptions.options">
</select>

Unfortunately the application I'm updating has lots of examples of static options but I need to bind it to a dynamic list.

I've managed to add a new field type that extends the select and am trying to map Desc to name and Code to value but it's not working as I had hoped.

formlyConfigProvider.setType({
        name: 'specialselect',
        templateUrl: getFieldTemplateUrl('select'),
        wrapper: commonWrappers,
        defaultOptions: {
            defaultValue: "",
            expressionProperties: {
                'templateOptions.options': function ($viewValue, $modelValue, scope) {

                    if (!scope.model.SomeObject.ItemCollection) {
                        return [];
                    }

                    var defaultOption = [{ name: 'Choose ...', value: '' }];

                    return _.union(defaultOption, _.map(scope.model.SomeObject.ItemCollection, function (value) {
                            return { name: value.Desc, value: value.Code };
                        }));
                }
            }
        }
    });

Ignoring the undefined which I've since fixed in my code, my list now contains: enter image description here

Issue 1: I'm not sure why I'm seeing string:JEEP in my value for some reason instead of just JEEP.

Update: So I've found other posts about Angular doing something to create a unique key which is why it's prefixing the value with the type. But I don't want that as I'm then going to have to strip it out before saving my object. What's the most efficient way of stripping out the type for the value? Or is there a better way of defining my field so that it doesn't have this behaviour.

Issue 2: How do I make this dynamic so that I can pass in the model property that contains my collection of items. Instead of using:

scope.model.SomeObject.ItemCollection

Solution

  • Turns out I could ignore the type prefixing the value. It seems to ignore it appropriately.

    Also for my dynamic list binding for the my select field I needed to set:

    "expressionProperties": {
      "templateOptions.options": "model.SomeObject.ItemCollection"
    }