我有一个带有响应式菜单的页面,如果菜单处于活动状态,则会触发灰色叠加层。我一直试图使用ng-if
显示此叠加层,但没有成功。我错过了什么?
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
之前,我尝试过这样的事情:
function NavController($scope) {
$scope.toggleOverlay = function() {
$scope.showOverlay = !$scope.showOverlay;
}
}
然后在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
无法获取值。
答案 0 :(得分:2)
您的叠加层不在控制器的范围内,因此无法访问showOverlay
。
要修复它,请将ng-controller
- 指令移动到容器元素中。像这样:
<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>