在 Ionic 的标题栏中动态显示主页按钮

Dynamically Show Home Button in Header Bar in Ionic

本文关键字:动态显示 主页 按钮 标题栏 Ionic      更新时间:2023-09-26

在我的Ionic应用程序中,我想在除主页以外的所有页面的标题栏中显示"回到主页"按钮。我尝试使用当 $state.current.name 等于 home 时设置为 false 的布尔值来执行此操作。

在 ng-show 指令中,我使用此布尔值来显示或隐藏主页按钮。不幸的是,布尔值始终设置为 true,因此该按钮也显示在主页上。我该如何解决这个问题?

我在应用程序中的控制器.js

.controller('mainController', function($scope, $state) {
    $scope.showHomeButton = true;
    if ($state.current.name == 'home') {
        $scope.showHomeButton = false;
    }
})

从索引中提取.html

<body ng-app="chartly" ng-controller="mainController">
  <ion-nav-bar class="bar-positive">
      <ion-nav-back-button class="button-clear">
          <i class="icon ion-ios-arrow-left"></i>
      </ion-nav-back-button>
      <ion-nav-buttons side="right" ng-show="showHomeButton">
          <a href="/#/home" class="button icon ion-home"></a>
      </ion-nav-buttons>
  </ion-nav-bar>
  <ion-nav-view>
  </ion-nav-view>

添加监视:

$scope.$watch(function(){
    return $state.current.name;
}, function(new){
    if (new === 'home') {
        $scope.showHomeButton = false;
    }
});

或者,如果这不起作用,则在主控制器中侦听事件$stateChangeSuccess

$rootScope.$on('$stateChangeSuccess',function(event, toState, toParams, fromState, fromParams){ 
if (toState.name === 'home') {
        $scope.showHomeButton = false;
    }
}

您是否尝试使用$location?

.controller('mainController', function($scope, $location) {
    if($location.path()!='#/home') {
        $scope.showHomeButton = true;
    }
})