Skip to content Skip to sidebar Skip to footer

Angularjs - Ng-options With Nested Json Based On Previous Select Option

i'm kind of new in Angular, and I facing a problem, I didn't find an answer that could help me, if some one could, thank you. :) I have a json like this: 'items': [ { 'post_type'

Solution 1:

You can add an ng-change to the first select that calls a function that loads the options

<select title="Pesquisar em:" class="form-control select-post-type"
    ng-model="widget.post_type"
    ng-options="item as item.label for item in post_types.items" ng-change="typeChanged()"></select>

And the function would load inside $scope.options the selected type options. Then you iterate over $scope.options in the second select


UPDATE:

I haven't tested the code, but it may guide you

Select:

<select title="Options:" class="form-control select-post-type"
      ng-model="widget.option"
      ng-options="option as option.name for option in options">

Change function (triggered when the value of the first select changes, so it will have the responsibility of loading the options of the post_type selected):

$scope.typeChanged = function() { 
    for (var i = 0; i < $scope.post_types.items.length; ++i) {
        if ($scope.post_types.items[i].label == $scope.widget.post_type) $scope.options = $scope.post_types.items[i].options || [];
    }
}

Solution 2:

widget.post_type should contain the selected item. So the other select can have options like option as option.name in widget.post_type.options. Note that you should probably have an options collection on each item if you want this to work.


Solution 3:

You can do this very easily using following technique. You just need to use the ng-model from the first select. See my approach:

<label>Pesquisar em:</label>

<select title="Pesquisar em:" class="form-control select-post-type"
    ng-model="firstSelect"
    ng-options="item as item.label for item in post_types.items"></select>

<select title="Second one" class="form-control select-post-type"
    ng-model="secondSelect" ng-show="firstSelect.options"
    ng-options="option as option.name for option in firstSelect.options"></select>

Post a Comment for "Angularjs - Ng-options With Nested Json Based On Previous Select Option"