【问题标题】:angular-ui/ui-select: how to set initial selected object correctlyangular-ui/ui-select:如何正确设置初始选定对象
【发布时间】: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 做类似的事情...
  • 不,我没有找到解决方案,对不起......我最终重复了选定的元素,即:初始选定的项目位于顶部(嗯,选定),如果你滚动向下,您可以在列表中的某个位置再次找到它。

标签: angularjs ui-select


【解决方案1】:

如果你想达到你提到的状态,那么只需将正确的引用传递给你的模型。

因此,在 fetchlabel 调用成功后,您可以设置标签中的值。现在在这个函数成功后你需要调用获取presentLabel的函数。

一旦你得到当前标签的数据,你就可以得到该对象在标签范围内的索引。

var idx;
_.find($scope.labels, function(label, labelIdx){ 
  if(label.labelId == parentLabel.labelId){ idx = labelIdx; return true;}; 
});

$scope.selectedLabel = {};
$scope.selectedLabel.selected = $scope.labels[idx];

这将解决您的目的。

【讨论】:

  • _.find() 与我在帖子末尾的for 有点相似?
  • 是的,你会得到同样的结果。但是下划线是非常推荐的实用程序,因为它提供了可读性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多