在AngularJS中,点击按钮时隐藏和显示

3

默认情况下我希望隐藏该值,在第一次单击按钮时显示该值。当您第二次单击相同的按钮时,它应该隐藏该值而不是显示该值。反之亦然。

这是我的HTML:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>AngularJS</title>
  <script 
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"> 
  </script>
  <script th:src="@{/main.js}"></script>   
<head>
<body ng-app="EmployeeManagement" ng-controller="EmployeeController">
<input type="button" value="Show Angular" ng-click="ShowHide()"/>
 <div ng-show = "IsVisible"> yes </div>
</body>
</html>

这是我的 JS 文件:

var app = angular.module("EmployeeManagement", []);
app.controller("EmployeeController", function($scope, $http) {
 $scope.ShowHide = function(){
     $scope.IsVisible =  true;
 }

有谁能告诉我如何实现这种情况?

3个回答

2

当你点击按钮时,应该使用$scope.IsVisible否定形式。这样,如果它是可见的,它就会隐藏,如果它是隐藏的,它就会可见:

试试这个:

最初的回答

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>AngularJS</title>
  <script 
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"> 
  </script>
  <script >
  var app = angular.module("EmployeeManagement", []);
    app.controller("EmployeeController", function($scope, $http) {
    $scope.ShowHide = function(){
        $scope.IsVisible =  !$scope.IsVisible;
    }
  })
 </script>   
<head>
<body ng-app="EmployeeManagement" ng-controller="EmployeeController">
<input type="button" value="Show Angular" ng-click="ShowHide()"/>
 <div ng-show = "IsVisible"> yes </div>
</body>
</html>


1

不要使用showHide函数,更好的名称应该是toggle()。在这个函数内部,不要设置$scope.IsVisible = true,而是可以像这样切换变量的值:!$scope.IsVisible


0

@karthick,你也可以在模板端完成它,而不需要控制器的任何交互。

  <!DOCTYPE HTML>
  <html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>AngularJS</title>
    <script 
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js"> 
    </script>
    <script >
    var app = angular.module("EmployeeManagement", []);
      app.controller("EmployeeController", function($scope, $http) {
    })
  </script>   
  <head>
  <body ng-app="EmployeeManagement" ng-controller="EmployeeController" ng-init="IsVisible=false">
  <input type="button" value="Show Angular" ng-click="IsVisible = !IsVisible"/>
  <div ng-show = "IsVisible"> yes </div>
  </body>
  </html>

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