How to create dictionary like model binding in AngularJS
11,132
<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 = [{
...
}];
}
Author by
MaciejLisCK
I am software Developer with at least 10 years programming experience. I did work in small startups as Full-Stack developer in London, medium softwarehouses as Senior .Net Developer up to big enterprises as .Net Architect.
Updated on August 22, 2022Comments
-
MaciejLisCK over 1 year
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. -
Sana Ahmed about 6 yearsif it is a dictionary coming from c#, would it work in the same way ?