Question

On my page I have dynamically generated input tags from database. Those fields could look like that:

<input id='customField-Street' type='text' />
<input id='customField-Height' type='text' />
<input id='customField-IsBlack' type="checkbox" />
<select id='customField-Car'>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
</select>

I need to find a way to set a model binding in following key-value format:

$scope.customFieldsDictionary = [{ 
    "Key": "customField-Street",
    "Value": "SomeStreet"
}, {
    "Key": "customField-Height",
    "Value": "125"
}, {
    "Key": "customField-IsBlack",
    "Value": "true"
}, {
    "Key": "customField-Car",
    "Value": "volvo"
}];

I need to have key-value format since my service accept custom data in that format.

Question: How to set AngularJS two way binding between input fields and $scope.customFieldsDictionary field in specified dictionary like format.

Was it helpful?

Solution

<div ng-repeat="obj in customFieldsDictionary">

    <input ng-model="obj.Value" id='{{obj.Key}}' ng-if="obj.Key == 
    'customField-Street' || obj.Key == 'customField-Height'" type='text'/>

    <input ng-model="obj.Value" id='{{obj.Key}}' ng-if="obj.Key == 
    'customField-IsBlack'" type="checkbox" />

    <select ng-model="obj.Value" id='{{obj.Key}}' ng-if="obj.Key == 
    'customField-Car'" ng-options="car for car in cars"></select>
</div>

Controller:

function ctrl($scope){
    $scope.cars = ["Volvo","Saab"];
    $scope.customFieldsDictionary = [{ 
        ...
    }];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top