Search code examples
angularjsdrop-down-menudropdownangular-ng-if

How to make ng-model work in ng-if?


I need to hide and show the div on change of select box, which is already inside ng-if. Here is the code. Please help me.

<div class="col-sm-6">
    <select name="" id="print-type" class="form-control" ng-model="printType">
        <option value="selectOne" selected>Select One</option>
        <option value="selectTwo">Wall Decoration</option>
    </select>
</div>
<div class="col-sm-6" ng-if="printType == 'selectTwo'">
     <select name="" id="wall-decoration" class="form-control" ng-model="wallDecorDropdown">
          <option value="One">Select One</option>
          <option value="two">Framed Print</option>
     </select>
</div>

<div ng-if="wallDecorDropdown == 'two'">Hi</div>

Thanks Very Much.


Solution

  • You are breaking the golden rule of always using an object in ng-model

    The problem is that ng-if creates a child scope. So when you change a primitive inside that child scope ng-model="wallDecorDropdown" it is hidden from the parent scope since primitives don't have inheritance the same way objects/arrays do

    Change to:

    <div class="col-sm-6" ng-if="printType == 'wallDecor'">
         <select name="" id="wall-decoration" class="form-control" ng-model="myScopeModel.wallDecorDropdown">
              <option value="One">Select One</option>
              <option value="two">Framed Print</option>
         </select>
    </div>
    
    <div ng-if="myScopeModel.wallDecorDropdown == 'two'">Hi</div>
    

    And in controller create an object that will be inherited by all child scopes

    $scope.myScopeModel ={}
    

    This 3 minute Egghead video is well worth watching to understand better.