AngularJS: ng-show

I am trying to show and hide the serial div accordingly using ng-show.

Here is my code:

angularExample.html

<!DOCTYPE html>
<html ng-app="Fino">
  <head>
    <link rel="stylesheet" type="text/css" href="scripts/bootstrap.min.css" />
    <script type="text/javascript" src="scripts/angular.min.js"></script>
    <script type="text/javascript" src="scripts/app.js"></script>
  </head>
  <body ng-controller="FinController as fin">
  <ul ng-repeat="emp in fin.employees" ng-show="fin.showDiv(0)">
  <li>Name:{{emp.name}}</li>
  <li>Age:{{emp.age}}</li>
  <li>Salary:{{emp.amount | currency}}</li>
  </ul> 
  <ul ng-repeat="emp in fin.employees" ng-show="fin.showDiv(1)">
  <li>Employee Name:{{emp.name}}</li>
  <li>Employee Age:{{emp.age}}</li>
  <li>Employee Salary:{{emp.amount | currency}}</li>
  </ul>
  </body>
</html>

App.js

var app=angular.module("Fino",[]);

app.controller("FinController",function(){
    var show=false;

    this.employees=totalemp;

    this.showDiv=function(param){
        if(param===1)
        {
            show=true;
        }
        return show;
    };

});


var totalemp=[
{
name:"abc",age:"20",amount:"120"
},
{
name:"pqr",age:"30",amount:"130"
},
{
name:"xyz",age:"40",amount:"140"
}
]

Conclusion:  enter image description here

I start with Angular js.I am not sure why my first div appears in the output.

+4
source share
2 answers

This is because you are referencing the same variable showin both. The variable showis common to both controllers, since the second cycle is executed, the value is changed. Thus, it displays both divs

It should be:

this.showDiv=function(param){
        if(param===1)
        {
            return true;
        }
        return false;
    };

EDIT:

Demo

+4
source

, AngularJS . showDiv ng-show.

show, param === 1 ( ). , show true, div .

, show false, param === 0 ( ), (return param === 1). .

+2

All Articles