Html 如何基于布尔值在 AngularJS 中切换 ng-show?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19018536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:47:23  来源:igfitidea点击:

How do I toggle an ng-show in AngularJS based on a boolean?

javascripthtmlangularjsng-show

提问by liamzebedee

I have a form for replying to messages that I want to show only when isReplyFormOpenis true, and everytime I click the reply button I want to toggle whether the form is shown or not. How can I do this?

我有一个用于回复消息的表单,仅在isReplyFormOpen为 true时才显示,每次单击回复按钮时,我都想切换是否显示该表单。我怎样才能做到这一点?

回答by Nitu Bansal

You just need to toggle the value of "isReplyFormOpen" on ng-click event

您只需要在 ng-click 事件上切换“isReplyFormOpen”的值

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
 <div ng-show="isReplyFormOpen" id="replyForm">
   </div>

回答by liamzebedee

Basically I solved it by NOT-ing the isReplyFormOpenvalue whenever it is clicked:

基本上我通过在点击时-ingisReplyFormOpen值来解决它:

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
    <!-- Form -->
</div>

回答by Andrii Motsyk

If based on click here it is:

如果基于点击这里是:

ng-click="orderReverse = orderReverse ? false : true"

回答by James Gentes

It's worth noting that if you have a button in Controller A and the element you want to show in Controller B, you may need to use dot notation to access the scope variable across controllers.

值得注意的是,如果您在控制器 A 中有一个按钮,而您想在控制器 B 中显示元素,则可能需要使用点表示法来跨控制器访问范围变量。

For example, this will notwork:

例如,这将无法正常工作:

<div ng-controller="ControllerA">
  <a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

To solve this, create a global variable (ie. in Controller A or your main Controller):

要解决此问题,请创建一个全局变量(即在控制器 A 或您的主控制器中):

.controller('ControllerA', function ($scope) {
  $scope.global = {};
}

Then add a 'global' prefix to your click and show variables:

然后为您的点击添加一个“全局”前缀并显示变量:

<div ng-controller="ControllerA">
  <a ng-click="global.isReplyFormOpen = !global.isReplyFormOpen">Reply</a>

  <div ng-controller="ControllerB">
    <div ng-show="global.isReplyFormOpen" id="replyForm">
    </div>
  </div>

</div>

For more detail, check out the Nested States & Nested Views in the Angular-UI documentation, watch a video, or read understanding scopes.

有关更多详细信息,请查看 Angular-UI 文档中嵌套状态和嵌套视图观看视频或阅读理解范围

回答by Vaibhav Ujjwal

If you have multiple Menus with Submenus, then you can go with the below solution.

如果您有多个带有子菜单的菜单,那么您可以使用以下解决方案。

HTML

HTML

          <ul class="sidebar-menu" id="nav-accordion">
             <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('dashboard')">
                      <i class="fa fa-book"></i>
                      <span>Dashboard</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showDash">
                      <li><a ng-class="{ active: isActive('/dashboard/loan')}" href="#/dashboard/loan">Loan</a></li>
                      <li><a ng-class="{ active: isActive('/dashboard/recovery')}" href="#/dashboard/recovery">Recovery</a></li>
                  </ul>
              </li>
              <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('customerCare')">
                      <i class="fa fa-book"></i>
                      <span>Customer Care</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showCC">
                      <li><a ng-class="{ active: isActive('/customerCare/eligibility')}" href="#/CC/eligibility">Eligibility</a></li>
                      <li><a ng-class="{ active: isActive('/customerCare/transaction')}" href="#/CC/transaction">Transaction</a></li>
                  </ul>
              </li>
          </ul>

There are two functions i have called first is ng-click = hasSubMenu('dashboard'). This function will be used to toggle the menu and it is explained in the code below. The ng-class="{ active: isActive('/customerCare/transaction')} it will add a class active to the current menu item.

我首先调用的两个函数是 ng-click = hasSubMenu('dashboard')。此函数将用于切换菜单,并在下面的代码中进行了解释。ng-class="{ active: isActive('/customerCare/transaction')} 它将添加一个类 active 到当前菜单项。

Now i have defined some functions in my app:

现在我已经在我的应用程序中定义了一些函数:

First, add a dependency $rootScope which is used to declare variables and functions. To learn more about $roootScope refer to the link : https://docs.angularjs.org/api/ng/service/$rootScope

首先,添加用于声明变量和函数的依赖项 $rootScope。要了解有关 $rootScope 的更多信息,请参阅链接:https://docs.angularjs.org/api/ng/service/ $rootScope

Here is my app file:

这是我的应用程序文件:

 $rootScope.isActive = function (viewLocation) { 
                return viewLocation === $location.path();
        };

The above function is used to add active class to the current menu item.

上述函数用于向当前菜单项添加活动类。

        $rootScope.showDash = false;
        $rootScope.showCC = false;

        var location = $location.url().split('/');

        if(location[1] == 'customerCare'){
            $rootScope.showCC = true;
        }
        else if(location[1]=='dashboard'){
            $rootScope.showDash = true;
        }

        $rootScope.hasSubMenu = function(menuType){
            if(menuType=='dashboard'){
                $rootScope.showCC = false;
                $rootScope.showDash = $rootScope.showDash === false ? true: false;
            }
            else if(menuType=='customerCare'){
                $rootScope.showDash = false;
                $rootScope.showCC = $rootScope.showCC === false ? true: false;
            }
        }

By default $rootScope.showDash and $rootScope.showCC are set to false. It will set the menus to closed when page is initially loaded. If you have more than two submenus add accordingly.

默认情况下,$rootScope.showDash 和 $rootScope.showCC 设置为 false。当页面最初加载时,它会将菜单设置为关闭。如果您有两个以上的子菜单,请相应添加。

hasSubMenu() function will work for toggling between the menus. I have added a small condition

hasSubMenu() 函数将用于在菜单之间切换。我添加了一个小条件

if(location[1] == 'customerCare'){
                $rootScope.showCC = true;
            }
            else if(location[1]=='dashboard'){
                $rootScope.showDash = true;
            }

it will remain the submenu open after reloading the page according to selected menu item.

根据所选菜单项重新加载页面后,它将保持子菜单打开。

I have defined my pages like:

我已经定义了我的页面,如:

$routeProvider
        .when('/dasboard/loan', {
            controller: 'LoanController',
            templateUrl: './views/loan/view.html',
            controllerAs: 'vm'
        })

You can use isActive() function only if you have a single menu without submenu. You can modify the code according to your requirement. Hope this will help. Have a great day :)

仅当您只有一个没有子菜单的菜单时,才可以使用 isActive() 函数。您可以根据需要修改代码。希望这会有所帮助。祝你有美好的一天 :)

回答by Abdallah Okasha

Here's an example to use ngclick & ng-if directives.

这是使用 ngclick 和 ng-if 指令的示例。

Note: that ng-if removes the element from the DOM, but ng-hide just hides the display of the element.

注意:ng-if 从 DOM 中删除元素,但 ng-hide 只是隐藏元素的显示。

<!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->

<input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
             Enter book name: <input type = "text" ng-model = "book.name"><br>
             Enter book category: <input type = "text" ng-model = "book.category"><br>
             Enter book price: <input type = "text" ng-model = "book.price"><br>
             Enter book author: <input type = "text" ng-model = "book.author"><br>


             You are entering book: {{book.bookDetails()}}
     </div>

    <script>
             var mainApp = angular.module("mainApp", []);

             mainApp.controller('bookController', function($scope) {
                $scope.book = {
                   name: "",
                   category: "",
                   price:"",
                   author: "",


                   bookDetails: function() {
                      var bookObject;
                      bookObject = $scope.book;
                      return "Book name: " + bookObject.name +  '\n' + "Book category: " + bookObject.category + "  \n" + "Book price: " + bookObject.price + "  \n" + "Book Author: " + bookObject.author;
                   }

                };
             });
    </script>