Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS, Populating dependent Combobox

Tags:

angularjs

What I am trying to achieve is to populate a child combobox with items which depend on a 'parent' combobox.

To clarify the problem, I have created a Fiddle under this link.

The combobox 'items' should populate every time the combobox 'group' has changed.

Controller:

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
}

View

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

I can't bring this to life declaratively. This should work without magic JavaScript - shouldn't it?

Thank you for your support

like image 729
qhaut Avatar asked Jan 12 '23 17:01

qhaut


1 Answers

You should refer currentGroup to populate the options inside items combobox:

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

You don't need $scope.currentItems at all. So just update the last 2 lines inside the controller to:

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

Now to remove the empty option, use super easy and light-weight ng-change:

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

Define the corresponding change handler in the controller:

$scope.groupChanged = function(){
    $scope.currentItem = $scope.currentGroup.Items[0];
}
like image 110
AlwaysALearner Avatar answered Jan 16 '23 18:01

AlwaysALearner