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


113

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

Answers:


218

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

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

我使用的正是这种方法,但是由于某种原因,ng-click中的本地布尔值“覆盖”了我在控制器$ scope中声明的布尔值。如果我通过控制器功能进行切换,问题就会消失:ng-click =“ toggleBoolean()”。知道为什么吗?
antoine 2015年

您是否在控制器中将布尔值设置为默认值?第一次在控制器函数中设置$ scope.isReplyFormOpen = falsel,然后尝试。
Nitu Bansal

1
哦,我确实在控制器中定义了布尔值。奇怪的是,此默认值是在页面加载时由ng-show正确读取的,但是在单击ng-click之后,它将仅更新此ng-show,而不更新页面中的其他值(所有注视着相同的布尔值-至少在理论上)...
antoine

3
解决了。因为我的ng-click嵌套在ng-repeat中,所以它创建了一个子作用域,当您尝试更改其值时,该子作用域隐藏了父布尔。参见stackoverflow.com/questions/15388344/…。根据Angular最佳实践,您应该在指令中将$ scope视为只读。
antoine

我将您的技巧用于ng-class<span ng-click="started=!started" ng-class="started ? 'btn-danger' : 'btn-success' ">+1。谢谢:)♥。
ivahidmontazer

30

基本上我解决了它的 -ing的isReplyFormOpen时,它被点击价值:

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

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

ng-init必要吗?
Charlie Schliesser 2014年

6
@CharlieS不需要,isReplyFormOpen undefined最初是!undefined == true
sceid 2014年


5

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

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

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

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

</div>

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

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

然后在您的click和show变量中添加“ global”前缀:

<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>

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


布尔值的最佳解决方案
maverickosama92

0

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

注意: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>

0

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

的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>

我首先调用了两个函数,即ng-click = hasSubMenu('dashboard')。此功能将用于切换菜单,下面的代码对此进行了说明。ng-class =“ {active:isActive('/ customerCare / transaction')}它将为当前菜单项添加一个活动类。

现在,我在我的应用程序中定义了一些功能:

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

这是我的应用程序文件:

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

上面的函数用于将活动类添加到当前菜单项。

        $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;
            }
        }

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

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

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

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

我的页面定义如下:

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.