Don Rhummy Don Rhummy - 4 months ago 12
AngularJS Question

How show diff. HTML based on property in angularjs?

I have a collection of objects that are of types:

text
,
selectoptions
and
multiselectoptions
. I need to display them as editable inputs based on their type.

For example, a text object:

<input type="text" name="caption" value="{{option.value}}" />


A selectoption/multiselectoptions:

<div ng-repeat="value in option.values">
<input type="text" name="{{option.id}}[value][{{value.id}}]" value="{{value.value}}" />
<input type="text" name="{{option.id}}[caption][{{value.id}}]" value="{{value.caption}}" />
</div>


Is this the correct way to do this? Is there a better way to represent it?

Example of the JSON objects:

FORM: {
options: [
{
type: "select",
values: [
{
value: 0,
caption: "Some option"
},
{
value: 1,
caption: "Some other option"
}
]
},
{
type: "text",
caption: "Some text item"
}
]
}

Answer

You could use ng-if to display the correct form element based on your model. Here is an example in plunker based on your code.

<form novalidate class="simple-form">
    <div ng-repeat="field in FORM.options">
        <input type="text" ng-model='field.caption' ng-if="field.type == 'text'" /><br />
        <div ng-if="field.type != 'text'">
             <div ng-repeat="value in field.values">
                Option: <input type="text" name="{{option.id}}[value][{{value.id}}]" value="{{value.value}}" /><br/>
                Caption: <input type="text" name="{{option.id}}[caption][{{value.id}}]" value="{{value.caption}}" /><br/>
             </div>
        </div>
    </div>
    <button ng-click="submit()">Save</button>
</form>

I check the type field.type and display different HTML in the main ng-repeat.

The app assign your model to FORM:

$scope.FORM =  {
    options: [
        {
            type: "select",
            values: [
                {
                    value: 0,
                    caption: "Some option"
                },
                {
                    value: 1,
                    caption: "Some other option"
                }
            ]
        },
        {
            type: "text",
            caption: "Some text item"
        }
    ]
};

I also added a submit button that display the model in the Javascript console, so you can see that the data is being updated when you change the values:

<button ng-click="submit()">Save</button>
Comments