program tip

부울을 기준으로 AngularJS에서 ng-show를 어떻게 전환합니까?

radiobox 2020. 7. 28. 08:23
반응형

부울을 기준으로 AngularJS에서 ng-show를 어떻게 전환합니까?


isReplyFormOpen사실 일 때만 표시하고 싶은 메시지에 답장하는 양식이 있는데 답장 버튼을 클릭 할 때마다 양식의 표시 여부를 전환하고 싶습니다. 어떻게해야합니까?


ng-click 이벤트에서 "isReplyFormOpen"값을 토글하면됩니다.

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

나는 기본적으로 그것을 해결 하지 -ing isReplyFormOpen가 클릭 할 때마다 값을 :

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

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

여기를 클릭하면 다음과 같습니다.

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

컨트롤러 A에 버튼이 있고 컨트롤러 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>

이 문제를 해결하려면 전역 변수를 만듭니다 (예 : 컨트롤러 A 또는 기본 컨트롤러에서).

.controller('ControllerA', function ($scope) {
  $scope.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>

자세한 내용 들어, 체크 아웃 각도-UI 문서의 중첩 미국 및 중첩보기 , 비디오를보고 , 또는 읽기 이해 범위를 .


다음은 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>

하위 메뉴가있는 메뉴가 여러 개인 경우 아래 해결 방법을 사용할 수 있습니다.

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')} 현재 메뉴 항목에 활성화 된 클래스를 추가합니다.

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

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.

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

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

참고URL : https://stackoverflow.com/questions/19018536/how-do-i-toggle-an-ng-show-in-angularjs-based-on-a-boolean

반응형