如何在AngularJS中创建类似字典的模型绑定

How to create dictionary like model binding in AngularJS

本文关键字:字典 模型 绑定 创建 AngularJS      更新时间:2023-09-26

在我的页面上,我从数据库中动态生成了输入标记。这些字段可能是这样的:

<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>

我需要找到一种方法来设置以下键值格式的模型绑定:

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

我需要键值格式,因为我的服务接受该格式的自定义数据。

问题:如何在输入字段和$scope.customFieldsDictionary字段之间以指定的类似字典的格式设置AngularJS双向绑定。

<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>

控制器:

function ctrl($scope){
    $scope.cars = ["Volvo","Saab"];
    $scope.customFieldsDictionary = [{ 
        ...
    }];
}