2014-11-24 79 views
8

这是我的用户界面视图中选择:角UI/UI的选择:如何设置初始选择的对象正确

<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'} 


......我说理论上,因为凭经验,我看到他们是不同的,因为角度增加了他们的东西(例如, $$hashKey__proto__)。

所以,因为中,$scope.selectedLabel.selected = $scope.passedLabel不匹配在对应的项的UI选择(它们不是相同的对象),并且因此,的该结果是这样的行为:

ui-select behavior with initial selection

如何正确设置初始选择?有没有一种方法可以使用id而不是对象comparisson?我想避免一个for这样的:

for (i=0; i<$scope.labels; i++) { 
     if ($scope.labels[i].labelId == $scope.passedLabel.labelId) { 
      $scope.selectedLabel.selected = $scope.labels[i] 
     } 
    } 

,我敢肯定,预期它的工作,但我将不得不调用for阿贾克斯返回之后...我有其他UI - 也选择

+0

您是否找到针对此问题的解决方案,其他的则是您建议的for循环?我有同样的问题,我真的不喜欢搜索和替换的初始价值的东西。这个问题的现场演示可以在[pnkrr]找到(http://plnkr.co/edit/bK6JNpIRL4jTQWt3AXey?p=preview)。当使用常规下拉菜单时,我们可以通过表达式来实现这一点,角度材料可以通过['ng-model =“foo”ng-model-options =“{trackBy:'$ value.id'}” ](https://github.com/angular/material/blob/master/src/components/select/select.js)。我真的想用UI选择类似的东西... – Pieter 2015-04-04 10:50:29

+0

不,我没有找到解决方案,对不起...我最终重复选定的元素,即:最初选择的项目是在顶部(好,选中),如果向下滚动,则可以在列表中的某处找到它。 – sports 2015-04-04 18:52:18

回答

5

如果您想实现您提到的状态,那么只需将正确的参考传递给您的模型即可。

因此,在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]; 

这会解决你的目的。

+2

'_。find()'在某种程度上类似于我在文章结尾的'for'? – sports 2014-11-24 16:42:28

+2

是的,你会得到同样的结果。然而下划线是非常值得推荐的实用工具,因为它提供了可读性 – 2014-11-24 18:02:51