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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20093645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:40:57  来源:igfitidea点击:

How to create dictionary like model binding in AngularJS

javascriptwcfangularjsdictionarymodel-binding

提问by MaciejLisCK

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.customFieldsDictionaryfield in specified dictionary like format.

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

采纳答案by AlwaysALearner

<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 = [{ 
        ...
    }];
}