Search code examples
angularjsangular-formly

Setting DefaultValue of a directive field type


Please look at the following jsbin

You will notice that there are two fields. One is a normal input while the other is a new field type that references exampleDirective. Please note...in my real application, these fields are pulling pulled from JSON and are not manually added to the fields array.

I set the DefaultValue on each record within the fields array. Again, these default values are being pulled from JSON.

The RegularInput field is properly displaying the default within its input field.

The DirectiveInput is not. Please look at the model and you will see that the default value was applied to the field itself and not the input field (or fields if I had multiple) within the directive.

Is there a way to make DefaultValue work in this type of situation? And if not...what would the best way to get the value that I am pulling from JSON to be placed on the directive fields?


Solution

  • I ended up fixing my issue by passing data INTO the directive.

    formlyConfig.setType(
    {
        name: 'dirTest1',
        template: '<div directive-test checked="to.IsChecked" amount="to.CoverageAmount"</div>'
    });
    

    With this approach, I can specify IsChecked and CoverageAmount in my directive and pass the values that I need when setting up the various inputs within the directive. So, when I push this field type to my fields array, I can easily set my values like so:

    var newRow = {
        key: TestKey,
        type: dirTest1,
        templateOptions: {
            CoverageAmount: 12345,
            IsChecked: true
        }
    };
    vm.fields[i].fieldGroup.push(newRow);