默认情况下,当您使用select
修改ng-options
绑定的源列表时,即使该项在新列表中完整存在,它也会清除所选列表项。我认为可能有一种方法可以告诉角度,如果它们具有相同的WhateverKey
属性,那么将它们视为相同的项目并且不要取消选择。有没有办法做到这一点?
在下面的示例中,选择新客户会重新绑定(思考:重新下载)可能位置列表,但所选位置($scope.Location
)仍然存在于新列表中,因此用户体验直觉说它应该被选中。
我明白问题在于它实际上是一个不同的角度对象键的参考对象。我想知道如何根据属性自动重新绑定对象(在本例中为LocationKey
),无需通过JavaScript循环来手动查找新列表中的相应对象。
function Ctrl($scope) {
$scope.Customers = [{CustomerKey: 1, CustomerCode: 'Customer1'},
{CustomerKey: 2, CustomerCode: 'Customer2'},
{CustomerKey: 3, CustomerCode: 'Customer3'}];
$scope.Locations = [{LocationKey: 1, LocationCode: 'Location1'},
{LocationKey: 2, LocationCode: 'Location2'},
{LocationKey: 3, LocationCode: 'Location3'}];
$scope.Customer = $scope.Customers[0];
$scope.Location = $scope.Locations[0];
$scope.SelectCustomer = function() {
$scope.Locations = angular.copy($scope.Locations);
}
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
<select ng-model="Customer"
ng-options="c as c.CustomerCode for c in Customers"
ng-change="SelectCustomer()"></select>
<select ng-model="Location"
ng-options="l as l.LocationCode for l in Locations"></select>
<div ng-bind="'Customer: ' + Customer.CustomerCode"></div>
<div ng-bind="'Location: ' + Location.LocationCode"></div>
</div>
&#13;
答案 0 :(得分:0)
$scope.SelectCustomer = function() {
$scope.Locations = angular.copy($scope.Locations);
$scope.Location = $scope.Locations.find(function(loc){
return loc.LocationKey === $scope.LocationKey;
}
}
很抱歉这个懒惰的回答。如果您可以在评论中正确格式化代码,那么本来是评论。