user4756836 user4756836 - 27 days ago 20
Javascript Question

Hide show div angular

I am trying to hide and show div on each button click. Basically, if the first button is clicked show the first div... if the second div is clicked show the second div. My issue is that it shows and hides div only ONCE.

HTML:

<div ng-app="sandbox">
<div layout="row" flex layout-align="center">
<md-button ng-click="div1=true">Div 1</md-button>
<md-button ng-click="div2=true">Div 2</md-button>
</div>
<section layout="row">
<div ng-hide="div2" ng-show="div1" flex>
<md-card>
<md-card-content>
<p>This is Div 1</p>
</md-card-content>
</md-card>
</div>
<div ng-hide="div1" ng-show="div2" id="div2" flex>
<md-card>
<md-card-content>
<p>This is Div 2</p>
</md-card-content>
</md-card>
</div>
</section>
</div>


Also want first div to show on page load, so tried this:

#div2 {
display:none;
}


but now it won't switch to
#div2
at all

JSFiddle Demo

Answer

Use ng-init to initialise the default state, and then use just one variable to define which one is visible.

<div ng-app="sandbox" ng-init="visibleDiv='div1'">
  <div layout="row" flex layout-align="center">
    <md-button ng-click="visibleDiv='div1'">Div 1</md-button>
    <md-button ng-click="visibleDiv='div2'">Div 2</md-button>
  </div>
  <section layout="row">
    <div ng-show="visibleDiv == 'div1'" flex>
      <md-card>
        <md-card-content>
          <p>This is Div 1</p>
        </md-card-content>
      </md-card>
    </div>
    <div ng-show="visibleDiv == 'div2'" id="div2" flex>
      <md-card>
        <md-card-content>
          <p>This is Div 2</p>
        </md-card-content>
      </md-card>
    </div>
  </section>
</div>

https://jsfiddle.net/fsxa8xcc/1/

Comments