2017-07-05 81 views
0

我有一個頁面具有響應菜單,並且在菜單處於活動狀態時觸發灰色覆蓋。我一直試圖用ng-if來展示這個覆蓋圖,但沒有成功。我錯過了什麼?如果ng-if爲真,則覆蓋div不會顯示

HTML

<header ng-controller="NavController"> 
    <div class="cover-header"> 
     <!-- Burger menu icon placement --> 
     <div class="navbar-header"> 
      <button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu" 
        aria-expanded="{{showOverlay}}"> 
       <span class="glyphicon glyphicon-menu-hamburger"></span> 
      </button> 
     </div> 
</header> 


<div class="container-burger-menu"> 
    <div class="collapse container-accordion" id="main-menu"> 
     <!-- menu items go here --> 
    </div> 
</div> 
<div class="overlay-nav" ng-if="showOverlay"> 

CSS

.overlay-nav { 
    //display:block; 
    width: 100%; 
    height: 100%; 
    background: rgba(0,0,0,0.5); 
    position: absolute; 
    top: 0; 
    left: 0; 
    z-index: 999; 
} 

控制器

function NavController($scope) { 
    $scope.$watch('showOverlay', function(){ 
     console.log("value is ", $scope.showOverlay); 
     $scope.showOverlay = !$scope.showOverlay; 
    }); 
} 

此前使用$scope.$watch,我已經試過這樣的事情:

​​

然後在HTML:

<button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu" 
       aria-expanded="{{showOverlay}}" ng-click="toggleOverlay()>  

任何答覆將不勝感激。謝謝。


編輯:我的最新嘗試:

HTML

<button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu" 
        ng-click="toggleOverlay()"> 

<!-- overlay --> 
<div class="overlay-nav" ng-if="nav.showOverlay"> 

控制器

function NavController($scope) { 

    $scope.nav = { showOverlay: '' }; 

    $scope.toggleOverlay = function() { 
     $scope.nav.showOverlay = !$scope.nav.showOverlay; 
    } 
} 

$scope.nav.showOverlay更改值就好了,但沒有被ng-if拾起。

回答

2

您的覆蓋圖不在控制器的範圍內,因此無法訪問showOverlay

要解決該問題,請將ng-controller-directive移動到容器元素中。像這樣:

<div ng-controller="NavController"> 
    <header> 
     <div class="cover-header"> 
      <!-- Burger menu icon placement --> 
      <div class="navbar-header"> 
       <button type="button" class="collapsed nav-burger-icon" data-toggle="collapse" data-target="#main-menu" 
         aria-expanded="{{showOverlay}}"> 
        <span class="glyphicon glyphicon-menu-hamburger"></span> 
       </button> 
      </div> 
    </header> 


    <div class="container-burger-menu"> 
     <div class="collapse container-accordion" id="main-menu"> 
      <!-- menu items go here --> 
     </div> 
    </div> 
    <div class="overlay-nav" ng-if="showOverlay"> 
</div> 
+1

Gah,並且所有這些我都認爲我的控制器有問題。謝謝Nikolaj,現在工作正常。 :) –