ng-options 和绑定到复杂的数据模型

ng-options and binding to complex data model

http://plnkr.co/edit/eayVNWWEXE6rUfddTdgg?p=info

我有这个客户对象

   $scope.customerFound = {
    "id":"1",
    "customerId":2,
    "customerLabel":"light", 
    "valueId":55,
    "valueLabel":"TOP"
  }

以及我通过 ng-options 循环的列表:

  $scope.customerList = [
      {
            "valueId":55,
            "valueLabel":"LUOL"
      },
      {
            "valueId":65,
            "valueLabel":"TOP"
      },
      {
            "valueId":75,
            "valueLabel":"BOT"
      },
    ]
};

html

  <select ng-model="customerFound" ng-options="customer.valueLabel for customer in customerList track by customer.valueLabel | orderBy:'valueLabel'">
        <option selected value="" disabled id="text-disabled">  Select </option>
  </select>

{{customerFound}}

plnkr: http://plnkr.co/edit/eayVNWWEXE6rUfddTdgg?p=info

如果您在我从下拉菜单 select 中注意到 plnkr,我的整个 customerFound 对象将更改为仅来自 custermorList 的两个属性。

有没有简单的方法来更新我的 customerFound 对象中的 valueId 和 valueLabel 而无需进行大量数据转换?

谢谢

我认为你应该稍微重组你的数据——如果你让你想要更改的两个属性成为它们自己的对象,那么它就变得非常简单:

http://plnkr.co/edit/betys07Cq9I1QRmP7HIs?p=preview

$scope.customerFound = {
  "id":"1",
  "customerId":2,
  "customerLabel":"light", 
  "value": { 
    "id":55,
    "label":"TOP"
  }
}

$scope.customerList = [
  {
    "id":55,
    "label":"LUOL"
  },
  {
    "id":65,
    "label":"TOP"
  },
  {
    "id":75,
    "label":"BOT"
  },
]

<select ng-model="customerFound.value" ng-options="value as value.label for value in customerList track by value.label | orderBy:'valueLabel'">
    <option selected value="" disabled id="text-disabled">  Select </option>
</select>

如果您无法重组数据,那么您可以这样做:

http://plnkr.co/edit/had9Q9qkmpfDYydUzBNE?p=preview

本质上,使用 tmp ng-model,并使用 ng-change 设置属性:

 $scope.setSelected = function(o) {
  for (var k in o) {
    if (o.hasOwnProperty(k)) {
      $scope.customerFound[k] = o[k];
    }
  }
}

<select ng-change="setSelected(tmp)" ng-model="tmp" ng-options="customer.valueLabel for customer in customerList track by customer.valueLabel | orderBy:'valueLabel'">
    <option selected value="" disabled id="text-disabled">  Select </option>
</select>

如果您不能按照其他一些 comments/answers 中的建议重新排列数据,我认为这里使用 ng-change 的版本可以回答您的问题:

$scope.updateCustomerFound = function() {
  $scope.customerFound.valueId = $scope.customerFoundSelect.valueId;
  $scope.customerFound.valueLabel = $scope.customerFoundSelect.valueLabel;
};

并更新您的 select

<select ng-model="customerFoundSelect" ng-change="updateCustomerFound()" ...>

我的分叉plunker.