Reputation: 653
I am trying to show and hide consecutive div's respectively 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"
}
]
Output:
I am a beginner to Angular js.I am not sure as to why my first div is appearing in the output.
Upvotes: 4
Views: 761
Reputation: 18566
It's because you're referring to same variable show
in both. The variable show
is common for both the controller so as the second loop runs, the value got changed. So it's displaying both divs
It must be:
this.showDiv=function(param){
if(param===1)
{
return true;
}
return false;
};
EDIT:
Upvotes: 4
Reputation: 3644
This is because AngularJS performce atleast two digest cycles. Meaning your showDiv
function will be executed atleast twice for every ng-show directive.
You change the value show
if param === 1
(and never change it back). This means in the second digest cycle the variable show
is already true
and the first div will get shown.
To fix this you can either change the variable show
to false if param === 0
(inside your function) or consider returning the boolean directly (return param === 1
). I would recommend the second approach.
Upvotes: 2