2014-11-24 62 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