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?

1
  • Have you tried changing "model": "address.street" to something like "model": "address" : { "street": ""}? Commented May 30, 2014 at 14:13

1 Answer 1

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">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.