Reputation: 1337
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
Upvotes: 0
Views: 1932
Reputation: 12022
After the first click, you set both div1
and div2
as true
. But you have ng-hide="div2" ng-show="div1"
where ng-show
and ng-hide
both will be always true
.
I have updated your fiddle and changed your code as below.
Fiddle: https://jsfiddle.net/balasuar/fsxa8xcc/2/
Note: On load, they both are invisible and if you want to show one of them you can use ng-init="show=div1"
<div ng-app="sandbox">
<div layout="row" flex layout-align="center">
<md-button ng-click="show='div1'">Div 1</md-button>
<md-button ng-click="show='div2'">Div 2</md-button>
</div>
<section layout="row">
<div ng-show="show=='div1'" flex>
<md-card>
<md-card-content>
<p>This is Div 1</p>
</md-card-content>
</md-card>
</div>
<div ng-show="show=='div2'" id="div2" flex>
<md-card>
<md-card-content>
<p>This is Div 2</p>
</md-card-content>
</md-card>
</div>
</section>
</div>
Upvotes: 1
Reputation: 10629
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/
Upvotes: 1