Search code examples
javascriptangularjsdrop-down-menuangularjs-ng-optionsangularjs-ng-show

How can i use values from ng-model for ng-show?


i'm a newb in angular and have some trouble to figure out how to use the values from ng-model in the correct way.
I made two drop-down lists and want to create a dependence between these two. The second list shall be displayed, depending on the user input of the first. In this case the user shall select the kind of fermentation of a beer (here Obergärig for top-fermented) and the second drop-down should only be shown if the user took 'Obergärig'. I tried it with ng-show, but it doesn't work and i have no idea why or even if i use it the right way. I would be very thankful if someone could give me a short explanation what i'm doing wrong.

Html for the first drop-down:

<div ng-controller="BierController">
<select ng-model="Bierart" ng-options="art as art.name for art in arten">
<option value="" disabled selected>Gärigkeit auswählen</option>
</select>
</div>

Html for the second drop-down:

<div ng-controller="OberController" ng-show="Bierart == 'Obergärig'">
<select ng-model="OberBier" ng-options="sorte as sorte.name for sorte in obere">
<option value="" disabled selected>Biersorte auswählen</option>
</select>
</div>

And here's the .js:

app.controller("BierController", function($scope){
$scope.arten=[
{name:'Obergärig'},
{name:'Untergärig'},
{name:'Keine Angabe'}
];});

app.controller("OberController", function($scope) {
$scope.obere=[
{name:'Ale'},
{name:'Altbier'},
{name:'Berliner Weiße'}
];});   

That's my first post here, so i'm thankful for every advise to improve the quality of this post. Also, please excuse my bad english.


Solution

  • Just do the next steps:

    1. Use the same controller for both selects.

    2. Create some $scope variable to save the condition of the first select.(e.g. $scope.selectedBeer)

    3. Set the condition i ng-show property of the second select.

    Example:

    JS file:

    app.controller("BierController", function($scope){
    $scope.arten=[
    {name:'Obergärig'},
    {name:'Untergärig'},
    {name:'Keine Angabe'}
    ];
    
    $scope.obere=[
    {name:'Ale'},
    {name:'Altbier'},
    {name:'Berliner Weiße'}
    ];
    
    $scope.selectedBeer = "";
    });
    

    HTML file:

    <div ng-controller="BierController">
    <select ng-model="selectedBeer" ng-options="art as art.name for art in arten">
    <option value="" disabled selected>Gärigkeit auswählen</option>
    </select>
    </div>
    
    <div ng-controller="BierController" ng-show="selectedBeer == 'Obergärig'">
    <select ng-model="OberBier" ng-options="sorte as sorte.name for sorte in obere">
    <option value="" disabled selected>Biersorte auswählen</option>
    </select>
    </div>
    

    I may have done some syntax mistakes as I was coding this without any IDE, but the main idea is described. Good luck!