【发布时间】:2015-01-21 17:46:48
【问题描述】:
这是我在视图中选择的用户界面:
<ui-select ng-model="selectedLabel.selected" ng-disabled="fetchingLabels || working">
<ui-select-match placeholder="">{{$select.selected.code}}</ui-select-match>
<ui-select-choices repeat="label in labels| filterBy: ['name', 'code']: $select.search">
<div ng-bind-html="label.code | highlight: $select.search"></div>
<small ng-bind-html="label.name | highlight: $select.search"></small>
</ui-select-choices>
</ui-select>
这是我控制器中的相关代码:
$scope.labels = [];
$scope.selectedLabel = {};
$scope.selectedLabel.selected = $scope.passedLabel; // This is an object passed
// from the previous controller.
// The scope comes with it.
$scope.fetchLabels(); // This fetches the labels from the server
// and puts them in $scope.labels
从服务器带来的标签理论上如下:
[{'labelId': 20, 'code': 'L20', 'name': 'some label'},
{'labelId': 21, 'code': 'L21', 'name': 'other label'}, ...]
从外部传递的标签“passedLabel”理论上也类似于$scope.labels 中的标签之一,例如:
passedLabel = {'labelId': 21, 'code': 'L21', 'name': 'other label'}
...我说理论上是因为,从经验上看,我发现它们是不同的,因为 Angular 给它们增加了一些东西(例如$$hashKey 或 __proto__)。
因此,由于 差异,$scope.selectedLabel.selected = $scope.passedLabel 与 ui-select 中的相应项目不匹配(它们不是同一个对象),因此,结果是这种行为:
如何正确设置初始选择?有没有办法可以使用 id 而不是对象比较?我想避免这样的for:
for (i=0; i<$scope.labels; i++) {
if ($scope.labels[i].labelId == $scope.passedLabel.labelId) {
$scope.selectedLabel.selected = $scope.labels[i]
}
}
我很确定它会按预期工作,但我必须在 ajax 返回后调用 for...而且我还有其他 ui-selects
【问题讨论】:
-
除了您建议的 for 循环之外,您是否找到了解决此问题的方法?我遇到了同样的问题,我真的不喜欢搜索和替换初始值的东西。可以在at plnkr 找到该问题的现场演示。当使用常规下拉菜单时,我们可以通过表达式来实现这一点,角度材料可以通过
ng-model="foo" ng-model-options="{ trackBy: '$value.id' }"来实现。我真的很想用 ui-select 做类似的事情... -
不,我没有找到解决方案,对不起......我最终重复了选定的元素,即:初始选定的项目位于顶部(嗯,选定),如果你滚动向下,您可以在列表中的某个位置再次找到它。