2014-07-16 108 views
1

我正在發送JSON對象以初始化某些輸入並在我的頁面上選擇值。該對象擁有一個ShipTo屬性。我希望下拉列表中填入這個初始值。出於某種原因,它不是填充,即使它們是相同的對象。我甚至在軌道中添加的,以確保它是基於公司名稱測試平等(不完全相信如果多數民衆贊成由意味着什麼軌道)這是我有:Angular ng選項選擇未設置爲初始值

的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

爲了測試對象的相同性,它不檢查屬性,它檢查對象地址。儘管它們是相同的,但它們不是同一個對象。而不是$ scope.vm.Shipto = vm.shiptos [1]; –

回答

0

不肯定跟蹤不是你在這裏找的。

這是NG選項你正在使用的語法:select as label for value in array

你有錯的部分是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選項select參數對象上的其他東西,所以該模型並不一定是整個對象。如果賬戶號碼是您唯一標識符的對象,你可以改變你的選項:

data-ng-options="shipto.ShipTo.AccountNumber as shipto.ShipTo.CompanyName for shipto in vm.shiptos

現在,選擇將默認只有在連接模式等於shipto.AccountNumber。下面是一個工作的例子jsfiddle:http://jsfiddle.net/ADukg/5392/