formly-js / angular-formly

JavaScript powered forms for AngularJS
http://docs.angular-formly.com
MIT License
2.23k stars 405 forks source link

fieldTransform doesn't work with asynchronously loaded fields #671

Closed tilwinjoy closed 8 years ago

tilwinjoy commented 8 years ago

Hi, I'm trying to make use of the fieldTransform option. But it doesn't seem to work with asynchronously loaded fields.

My fieldTransform function is only invoked with an empty array [] (initial value), later when the actual data is fetched, formly directly tries to use it without transforming it first (of course it causes errors complaining that the data structure is incorrect).

For some reason I'm not able to save the JSBin (the save request stays in pending state) right now, I'll add one when I switch from this network.

Reproducing this is very easy, just add

 formlyConfig.extras.fieldTransform.push(function(fields,model){
     console.log(fields); // prints [ ]  once
     return model;
 });

to the official json-powered example and we can see that the fieldTransform function doesn't trigger when the actual data is received.

Shouldn't we be passing the data to fieldTransform functions on model changes before using it? or am I doing something wrong?

kentcdodds commented 8 years ago

You should hide your form behind ng-if="vm.fields.length" which will prevent Angular from compiling the form until your fields have loaded.

tilwinjoy commented 8 years ago

Yea that'd do it. But what if I'm pushing fields dynamically..? I'm not sure if that is supported, so to be on the safer side for now I added the transformation logic in the service that fetches data.

kentcdodds commented 8 years ago

Yeah, adding fields dynamically isn't well supported. Best to have them all at compile time and hide the ones that shouldn't be showing.