最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create dictionary like model binding in AngularJS - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Nov 20, 2013 at 10:41 MaciejLisCKMaciejLisCK 3,9845 gold badges33 silver badges40 bronze badges 1
  • did you send dictionary from C#? – Sana Commented Apr 3, 2018 at 11:53
Add a ment  | 

1 Answer 1

Reset to default 4
<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 = [{ 
        ...
    }];
}
发布评论

评论列表(0)

  1. 暂无评论