AngularJS, Populating dependent Combobox

前端 未结 4 1381
鱼传尺愫
鱼传尺愫 2021-01-03 07:25

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

To clarify the - or better my - problem, I have created

相关标签:
4条回答
  • 2021-01-03 07:54

    There is other solution to this kind of issues. That is to broadcast.

    Do brodcast after you got the data. In this example data came from Ajax call.

    $http.get('/SampleProgram/get_all_users').success(function(rsList){
           $scope.users =  rsList;
           $scope.$broadcast('I got all the users');
        });
    

    There should be listeners who always keeps their ears up for your broadcast message.

    $scope.$on('I got all the users', function () {
            alert("Hey All the users are here already let's make another ajax call with those users");
        })
    
    0 讨论(0)
  • 2021-01-03 07:55

    You can add a watcher to the controller like this. You can also remove the empty item when you pick different value of the first drop down list.

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

    Demo

    0 讨论(0)
  • 2021-01-03 08:00

    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 dont 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];
    }
    
    0 讨论(0)
  • 2021-01-03 08:07

    This should be what you're after:

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

    How this works is its using the select as label for item in group syntax. So for the first select box, whatever the user selects will become the object bound to currentGroup. A similar thing is done for currentItem

    We can then, optionally, use a $watch expression to be notified of that update and ensure that currentItem updates to the first item in the new group's Items array.

    0 讨论(0)
提交回复
热议问题