Error showing/hiding Div with Angular.js

Asked

Viewed 984 times

3

I need to hide fields using Angular JS, after clicking a button will be displayed to label down below:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">

<div>
    <input type="button" ng-model="btnArea" ng-init="btnArea = true" value="Áreas">
    <input type="button" ng-model="btnPonto" ng-init="btnPonto = true" value="Pontos">
</div>

<div ng-if="btnArea">
    <h1>Áreas</h1>
    <p>Welcome to my Áreas.</p>
    <hr>
</div>

<div ng-if="btnPonto">
    <h1>Pontos</h1>
    <p>Welcome to my Pontos.</p>
    <hr>
</div>

Link: Jseddle

1 answer

4


You can make an event allied to the directive ngClick, that will detect the click on the element, see the example:

ng-click="btnArea = !btnArea; btnPonto = false"
ng-click="btnPonto = !btnPonto; btnArea = false"

<input type="button" ng-model="btnArea"  ng-click="btnArea = !btnArea; btnPonto = false" value="Áreas">
<input type="button" ng-model="btnPonto" ng-click="btnPonto = !btnPonto; btnArea = false" value="Pontos">

This will create a "toggle" event by switching the value between true and false every click. The second part of ngClick will only leave the value of the other element as false, so it will be hidden when the other is displayed.


Simplifying your code as you want to start the display with the divs hidden, your code would look like this:

<div>
   <input type="button" ng-model="btnArea"  ng-click="btnArea = !btnArea; btnPonto = false"   value="Áreas">
   <input type="button" ng-model="btnPonto" ng-click="btnPonto = !btnPonto; btnArea = false" value="Pontos">
</div>

<div ng-if="btnArea">[...]</div>
<div ng-if="btnPonto">[...]</div>

See your updated example.

  • How to hide the other field ??

  • @alexjosesilva then, each button has its own ng-click that controls the display of the corresponding div.

  • happens that it is displayed the two fields at the same time...

  • It happens that in the example is being displayed both at the same time...

  • @alexjosesilva But what do you want to do? display only one or the other?

  • The initial idea is to display only the field after clicking the button and hiding another field...some @celsomtrindade tip

  • @alexjosesilva updated my answer, see if this is what you seek.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.