2

I have a working angular form with a dynamic model.

<input type="text" ng-model="formData[component.model]">

component.model is retrieved from a json structure that looks like this:

{
    "components": [
        {
            "model": "address.street"
        },
        {
            "model": "address.postcode"
        },
        {
            "model": "adress.city"
        }
    ]
}

This works fine, except the resulting json that is submitted by the form is flat and looks like this:

{
    "name": "John",
    "address.street": "kingsway road",
    "address.postcode": "SE16EH",
    "address.city": "London"
}

And I need more complex json like:

{
    "name": "John",
    "address": {
        "street": "kingsway road",
        "postcode": "SE16EH",
        "city": "London"
    }
}

Everything works fine when I hardcode the ng-model to for example:

ng-model="formData.address.street"

But with the dynamic stuff the resulting json is flat.

Does anyone know how I can get this to work?

  • Have you tried changing `"model": "address.street"` to something like `"model": "address" : { "street": ""}`? – TMH May 30 '14 at 14:13

1 Answers1

0

I was facing the same problem as you and I finally found a solution: https://stackoverflow.com/a/32096328/7126683

So you just have to create a new directive like that one:

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
return {
    restrict: 'A',
    terminal: true,
    priority: 100000,
    link: function (scope, elem) {
        var name = $parse(elem.attr('dynamic-model'))(scope);
        elem.removeAttr('dynamic-model');
        elem.attr('ng-model', name);
        $compile(elem)(scope);
    }
};

And in your template, replace the ng-model with the dynamic one.

<input dynamic-model="'formData.' + component.model" type="text">