简体   繁体   English

AngularJS:ng-show

[英]AngularJS: ng-show

I am trying to show and hide consecutive div's respectively using ng-show. 我试图使用ng-show分别显示和隐藏连续的div。

Here is my code: 这是我的代码:

angularExample.html 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 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. 我是Angular js的初学者。我不确定为什么我的第一个div出现在输出中。

It's because you're referring to same variable show in both. 这是因为你指的是同一个变量show在这两个。 The variable show is common for both the controller so as the second loop runs, the value got changed. 变量show对于控制器都是通用的,因此第二个循环运行时,值已更改。 So it's displaying both divs 所以它显示两个div

It must be: 肯定是:

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

EDIT: 编辑:

DEMO DEMO

This is because AngularJS performce atleast two digest cycles. 这是因为AngularJS执行至少两个摘要周期。 Meaning your showDiv function will be executed atleast twice for every ng-show directive. 这意味着对于每个ng-show指令, showDiv函数将至少执行两次。

You change the value show if param === 1 (and never change it back). 如果param === 1则更改值show (并且永远不会将其更改)。 This means in the second digest cycle the variable show is already true and the first div will get shown. 这意味着在第二个摘要周期中,变量show已经为true并且将显示第一个div。

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 ). 要修复此问题,您可以将变量show更改为false,如果param === 0 (在函数内)或考虑直接return param === 1 boolean( return param === 1 )。 I would recommend the second approach. 我会推荐第二种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM