2013-08-06 63 views
4

我想要實現的是使用依賴於「父」組合框的項來填充子組合框。爲了澄清 - 或更好的我 - 問題,我有created a Fiddle under this linkAngularJS,填充依賴Combobox

每當組合框「組」已更改時,組合框'項目'應該填充。

控制器:

function Controller($scope) { 

var groups = [ ]; // ommitted for the sake of clarity 

$scope.groups = groups;     // <- linked to cboGroup 
$scope.currentGroup = groups[0];  // <- should be updated from combobox 
$scope.currentItems = $scope.currentGroup.Items; // <- linked to cboItems 
$scope.currentItem = $scope.currentItems[0];  // <- should be updated from cboItems 
} 

查看

<select data-ng-model="currentGroup" data-ng-options="group.Name for group in groups"></select> 
<select data-ng-model="currentItem" data-ng-options="item.Name for item in currentItems"></select> 

我不能把這個生活聲明。這應該沒有魔術的JavaScript - 不應該嗎?

感謝您的支持,並有一個偉大的日子,半滑舌鰨

+0

當第一個選擇列表更改時,Codezilla的解決方案不會刪除空項目。檢查我的解決方案。 – zsong

回答

7

你應該參考currentGroup填充選項裏面項目組合框:

<select data-ng-model="currentItem" data-ng-options="item.Name for item in currentGroup.Items"></select> 

你不需要$範圍。當前的項目。所以只需更新最後兩行控制器裏面:

$scope.currentItem = $scope.currentGroup.Items[0]; 

我們刪除空選項,使用超方便,重量輕NG-變化

<select data-ng-model="currentItem" data-ng-options="item.Name for item in currentGroup.Items" ng-change="groupChanged()"></select> 

定義相應的變化控制器中的處理器:

$scope.groupChanged = function(){ 
    $scope.currentItem = $scope.currentGroup.Items[0]; 
} 
+0

當第一個選擇列表更改時,您的解決方案不會刪除空白項目。 – zsong

+0

@SZA我不值得讚賞。提問者問題中的最後2行($ scope.currentItems = something和$ scope.currentItem = something)是完全不必要的。如果刪除它們,您會看到所有選擇都顯示空白選項。而且可能是提問者更喜歡讓他們超過$ watch的性能影響。 – AlwaysALearner

+0

@qhaut我已更新我的答案以解決空白選項的問題。 – AlwaysALearner

1

您可以像這樣向控制器添加一個觀察器。 當您選擇第一個下拉列表的不同值時,您也可以刪除空的項目。

$scope.$watch('currentGroup', function() { 
    $scope.currentItems = $scope.currentGroup.Items; 
    $scope.currentItem = $scope.currentGroup.Items[0]; 
}); 

Demo

+1

當你可以直接引用'currentGroup.Items'(正如[Codezilla](http://stackoverflow.com/a/18082742/2057033)指出的那樣)添加一個昂貴的觀察器時,這是一個壞主意。爲了使用列表中的第一個填充當前項目,最好使用'ngChange'。 – Blackhole

+0

@Blackhole當第一個ddl更改時,您的解決方案不會刪除空項目。 – zsong

+0

@zsong如果將項目設置爲選中狀態,則不會像系列依賴於選擇框一樣工作。將第一個選項設置爲選定不會在下一個選擇框中輸入數值,然後在ng-change中輸入它們。有什麼辦法保持默認選擇的文本總是 – anam

1

這應該是你追求的:它在group語法使用selectlabelitem

http://jsfiddle.net/TsxTU/1/

這是如何工作的。因此,對於第一個選擇框,無論用戶選擇什麼,都將成爲綁定到currentGroup的對象。類似的事情是爲currentItem

完畢後,我們就可以任選,新組的Items陣列中使用$watch表達被通知該更新,並確保currentItem更新的第一個項目。