Can I use ng-click with ng-if to hide and show two different sections simultaneously

1.1k Views Asked by At

I'm working on an app in angularjs and trying to do something directly in the DOM. While I know this is not the greatest practice, it would be pretty practical in this case since I'm specifically trying to circumvent the controller. I tried to hook a button into ng-click with two functions true and false, then using ng-if to show and hide a section. Two functions because there are two sections. I'd like to get it to where if one button is clicked one section shows while the other hides and vice versa. It sort of works, but it will never get hide the first section. Also, in certain attempts, I got it sort of working but it would not default to any one element on load. Any ideas? My code looks something like:

<button class="add col-xs-6 col-sm-6 col-md-3 col-lg-3 add-btn" ng-model="showThis=true" ng-click="showMe=false; showThis=true">Add</button>
<button class="edit col-xs-6 col-sm-6 col-md-3 col-lg-3 edit-btn" ng-click="showMe=true; showThis=false">Edit</button>

<div ng-if="showThis">
    {A Section of Code}
</div>

<div ng-if="showME">
    {Another Section of Code}
</div>
1

There are 1 best solutions below

4
On

I would set a single variable, and then use it to toggle between the two divs:

<button class="add col-xs-6 col-sm-6 col-md-3 col-lg-3 add-btn" ng-model="showMe=true" ng-click="showMe=false">Add</button>
<button class="edit col-xs-6 col-sm-6 col-md-3 col-lg-3 edit-btn" ng-click="showMe=true">Edit</button>

<div ng-if="showMe">
    {A Section of Code}
</div>

<div ng-if="!showMe">
    {Another Section of Code}
</div>

If showMe is true, the top block will display, and the ! or NOT operator will hide the second block (!true == false).