我发送一个JSON对象,以便在我的页面上初始化一些输入和选择值。该对象包含ShipTo属性。我希望下拉列表中填充此初始值。由于某种原因,即使它们是同一个对象,它也不会填充。我甚至在一个轨道中添加了以确保它是基于CompanyName测试相等性(不完全确定那是什么轨道的意思)这是我所拥有的:
JSON对象:
{
"AccountNumber": "12345",
"Email": null,
"CompanyName": "HK Electric",
"Inactive": false,
"PhoneNumbers": null,
"ChildOfCustomer": "00000000-0000-0000-0000-000000000000",
"Id": "a4aab309-321c-4b09-969c-073eb83b90ad",
"ModifiedBy": null,
"ModifiedOn": "2014-07-16T18:46:52.065Z",
"CreatedBy": null,
"CreatedOn": "2014-07-16T18:46:52.065Z",
"IsDeleted": false
}
vm.shiptos:
[
{
"ShipTo": {
"AccountNumber": "1234",
"Email": null,
"CompanyName": "Mk Mechanical",
"Inactive": false,
"PhoneNumbers": null,
"ChildOfCustomer": "00000000-0000-0000-0000-000000000000",
"Id": "b90f9b8c-3910-43ec-8c14-6294155ce855",
"ModifiedBy": null,
"ModifiedOn": "2014-07-15T23:03:58.47Z",
"CreatedBy": null,
"CreatedOn": "2014-07-15T23:03:58.47Z",
"IsDeleted": false
},
"Addresses": [],
"Customer": null,
"Job": null,
"Orders": []
},
{
"ShipTo": {
"AccountNumber": "12345",
"Email": null,
"CompanyName": "HK Electric",
"Inactive": false,
"PhoneNumbers": null,
"ChildOfCustomer": "00000000-0000-0000-0000-000000000000",
"Id": "a4aab309-321c-4b09-969c-073eb83b90ad",
"ModifiedBy": null,
"ModifiedOn": "2014-07-16T18:46:52.065Z",
"CreatedBy": null,
"CreatedOn": "2014-07-16T18:46:52.065Z",
"IsDeleted": false
},
"Addresses": [],
"Customer": null,
"Job": null,
"Orders": []
}
]
我的HTML中的ngoptions语句:
<select id="ddlShipto" name="ddlShipto" data-ng-model="vm.Shipto" data-ng-options="shipto as shipto.ShipTo.CompanyName for shipto in vm.shiptos track by shipto.ShipTo.CompanyName" class="form-control FloatLeft" required>
<option selected="selected" value="">--Select One--</option>
</select>
答案 0 :(得分:0)
不确定跟踪是不是您正在寻找的内容。
这是您正在使用的ng-options语法:select as label for value in array
您错误的部分是select
参数。此参数的表达式与模型进行相等性检查以确定它是否匹配(并将自动设置所选选项等)。所以,现在你的select参数是shipto
。这意味着,为了默认值,您的模型需要等于vm.shiptos
中的对象。
以下是两个选项:
第一个选项是遍历vm.shiptos
并将模型设置为您想要默认的模型。例如:
angular.forEach($scope.vm.shiptos,function(el,i){
//check objects against the JSON object and set the model to the object if desired
if (el.ShipTo.AccountNumber === jsonObject.AccountNumber){
theModelForNgOptions = el;
}
};
您拥有的第二个选项是将ng-options select
参数更改为对象上的其他参数,以便模型不必是整个对象。如果AccountNumber是您对这些对象的唯一标识符,则可以将选项更改为:
data-ng-options="shipto.ShipTo.AccountNumber as shipto.ShipTo.CompanyName for shipto in vm.shiptos
现在,只有附加的模型等于shipto.AccountNumber
时,选择才会默认。以下是工作中的一个示例jsfiddle:http://jsfiddle.net/ADukg/5392/