[英]Angular ng-options select not being set to initial value
我正在發送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>
不確定track by不是您在這里尋找的東西。
這是您使用的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
,select才會默認。 這是工作中的示例jsfiddle: http : //jsfiddle.net/ADukg/5392/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.