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

时间:2016-01-28 15:45:17

标签: javascript angularjs ionic-framework

在我的Ionic应用程序中,我想在除主页之外的所有页面上的标题栏中显示“返回主页”按钮。我试图用$ state.current.name等于home时设置为false的布尔值来做这个。

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

app.js中的我的控制器

.controller('mainController', function($scope, $state) {
    $scope.showHomeButton = true;

    if ($state.current.name == 'home') {
        $scope.showHomeButton = false;
    }
})

从index.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>

2 个答案:

答案 0 :(得分:0)

添加手表:

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

}

答案 1 :(得分:0)

您是否尝试使用$ location?

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