How to create a dictionary like model binding in AngularJS

On my page, I have dynamically generated input tags from the database. These fields may look like this:

<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 the model binding in the following key value:

$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 a key format, since my service accepts user data in this format.

Question : How to establish two-way AngularJS binding between input fields and a field $scope.customFieldsDictionaryin a specified dictionary, such as a format.

+4
source share
1 answer
<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 = [{ 
        ...
    }];
}
+4
source

All Articles