FlyingCat
FlyingCat

Reputation: 14250

How to show and hide in angular in my case

I want to show/hide some elements when user clicks certain buttons

I have 3 buttons.

<a href='#' ng-click = 'show()'>button 1</a>
<a href='#' ng-click = 'show()>button 2</a>
<a href='#' ng-click = 'show()>button 3</a>

coordinate with 3 elements

<img src='img1' ng-show='img1Show'/>
<img src='img1' ng-show='img2Show'/>
<img src='img1' ng-show='img3Show'/>

under my controller

I have

    $scope.img1Show = true;
    $scope.img2Show = true;
    $scope.img3Show = true;

$scope.show = function(){
      //I want to control show and hide status 
}

Click once on button 1 will show the image1 and click again will hide the image1.

I want to know the most effective way of doing this. Do I really need img1Show to img3Show? Thanks.

Upvotes: 0

Views: 71

Answers (2)

Eric Chen
Eric Chen

Reputation: 3708

I write a live demo for you. check it out at http://plnkr.co/edit/jAWkDU

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <a href="#" ng-click="show1 = true">show 1</a>
    <a href="#" ng-click="show2 = true">show 2</a>
    <a href="#" ng-click="show2 != show2">toggle 2</a>


    <h1 ng-show="show1">11111</h1>
    <h1 ng-show="show2">22222</h1>
  </body>

</html>

Upvotes: 1

Chen-Tsu Lin
Chen-Tsu Lin

Reputation: 23214

Angular is a data binding framework. You need three variable to mark status for each img indeed.

But show() is not required.

You can directly toggle them by ng-click:

<a href='#' ng-click="img1Show = !img1Show">button 1</a>
<a href='#' ng-click="img2Show = !img2Show">button 2</a>
<a href='#' ng-click="img3Show = !img3Show">button 3</a>

Upvotes: 1

Related Questions