Search code examples
javascriptjqueryangularjsdynamicangular-ngmodel

AngularJS: Assign NgModel dynamically


I've got a controller in which I've got an array called fields. This array has the following structure (with some data as an example):

[
    {
        "name": "Demarcación",
        "type": "multiple",
        "scope": "restricted",
        "icon": "location-arrow",
        "order": 1,
        "id": 1,
        "possible_values": [
            {
                "id": 1,
                "field_id": 1,
                "name": "Demarcación 1"
            },
            {
                "id": 2,
                "field_id": 1,
                "name": "Demarcación 2"
            },
            {
                "id": 3,
                "field_id": 1,
                "name": "Demarcación 3"
            }
        ],
        "values": [
            {
                "id": 3,
                "value": "Demarcación 3"
            }
        ]
    },
    ...
]

Then, I want to create a form where the inputs are consctructed dynamically depending on the fields' type and scope. So, if the scope equals free, for example, then a textarea is added. Otherwise, an input text is added.

I need to perform some Javascript initialization depending on the field type, too, so - for example - if the scope is restricted I need to initialize a JQuery plugin on that input.

I've tried to set a function where I construct the HTML string and then print it in a ngRepeat, but I get the text as plain text (even using $sce.trustAsHtml()), without luck.

The question

Is there any way that I can write dynamically the inputs / html to add to document - and process some Javascript logic - and to which I can attach dynamically some AngularJS properties (like ngModel so its values get data-binded with the object)?

The inputs would be inside an ngRepeat directive, so I have access to the objects iterated and I can pass them as variables into a function.

Thank you!


Solution

  • I think what you are looking for is the $compile service

    Angular Documentation for $compile

    $compile(element.contents())(scope);
    

    Example in plunkr