如何在AngularJS中根据模型条件隐藏和显示div?

10

我想基于复选框的勾选状态来隐藏/显示一个div,这看起来很简单。我将复选框的值存储在模型中,并在

中使用它。我做错了什么?

<div ng-app='visibleApp'>
    <div ng-controller='myController'>
         <input type="checkbox" name="hideBasicInfo" ng-model="hideBasicInfo">hide the basic information section
         <div ng-show="{{!hideBasicInfo}}">
             <label for="firstName">First Name:</label>
             <input type="text" name="firstName" ng-model="firstName"/></br>

             <label for="middleName">Middle Name:</label>
             <input type="text" name="middleName" ng-model="middleName"/></br>
             <label for="lastName">Last Name:</label>
             <input type="text" name="lastName" ng-model="lastName"/>
         </div>
         <hr/>
         <div>
             <h4>Debug Information</h4>
             hideBasicInfo: {{hideBasicInfo}}<br/>
             !hideBasicInfo: {{!hideBasicInfo}}
         </div>
     </div>
</div>

JS文件:

var visibleApp = angular.module('visibleApp',[]);

visibleApp.controller('myController', function($scope){
     $scope.data = "my data";
     $scope.hideBasicInfo = false; 
});

谢谢。

请查看 fiddle


2
你不需要使用 {{ }}。 - Mike Robinson
3个回答

13

就快到了...

 <div ng-hide="hideBasicInfo">
    ...
 </div>

无需使用模板大括号 ( {{}} )。


0
<div ng-show='One'>
 <p>Section One</p>
</div>

<div ng-show='Two'>
 <p>Section Two</p>
</div>

<div ng-show='Three'>
 <p>Section Three</p>
</div>

<!-- Navigation -->
<nav>
 <a href='#' ng-click='showOne'> Show Div One </a>
 <a href='#' ng-click='showTwo'> Show Div Two </a>
 <a href='#' ng-click='showThree'> Show Div Three </a>
</nav>

也许解决方案更明显的方法是提供一些解释? - Scorpio
只需运行以下代码, <!DOCTYPE html><html> <head> <script src="angular.js"></script> </head> <body ng-app> <h3>1. 显示</h3> <label>显示正方形:<input type="checkbox" ng-model="mustShow" /></label><br /> <div ng-show="mustShow" style="width: 50px; height: 50px; background-color: red;"></div><br /> <br /> <h3>2. 隐藏</h3> <label>隐藏正方形:<input type="checkbox" ng-model="mustHide" /></label><br /> <div ng-hide="mustHide" style="width: 50px; height: 50px; background-color: green;"></div> </body> </html> - Saravanan R
ngShow指令根据提供给ngShow属性的表达式来显示或隐藏给定的HTML元素。通过在元素上添加或删除.ng-hide CSS类来显示或隐藏该元素。.ng-hide CSS类在AngularJS中预定义,并将显示样式设置为none(使用!important标志)。对于CSP模式,请将angular-csp.css添加到您的HTML文件中(请参见ngCsp)。 - Saravanan R

0
Execute this code:`enter code here`
<!DOCTYPE html>
<html>
<head>
  <script src="angular.js"></script>
</head>

<body ng-app>
  <h3>1. Show</h3>
  <label>Show the square: <input type="checkbox" ng-model="mustShow" /></label><br />
  <div ng-show="mustShow" style="width: 50px; height: 50px; background-color: red;"></div><br />
  <br />
  <h3>2. Hide</h3>
  <label>Hide the square: <input type="checkbox" ng-model="mustHide" /></label><br />
  <div ng-hide="mustHide" style="width: 50px; height: 50px; background-color: green;"></div>
</body>
</html>

3
尽管代码备受赞赏,但它应该始终配有相应的解释。这并不一定要很长,但是必须有。 - peterh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接