Conditional nav buttons between different controllers ($scope)


#1

Hello Everyone,
I found a task which is challenging for me to solve, is there any way to put the nav button conditionally when changing from one state to other? (using $state.go()). I’ve gone through the similar problem with the same $scope what about the different $scope

Thanks in advance.


#2

Could you define a service to do it? this way you would not have to care about different scopes.


#3

If changing from one “state” to another and assuming each state inserts an via it’s html you can just add an ion-nav-buttons directive in your new states html, this will render a new button in the header when you enter that state, e.g:

  • if I added the below html under the ion-view element for the templateUrl for the state i was navigating to, it would add the NewButton button to the right hand side of the header bar when i navigate to that state.
<ion-nav-buttons side=“secondary” >
	<button class=“button button-clear”>NewButton
	</button >
</ion-nav-buttons >

#4

Thanks @jawache and @gmarziou :slight_smile:
My need is to create buttons only if user go through specific state, buttons are not static for that view. It’s an accept button on top, if user go from other view it will be just a view without any secondary button


#5

So you are saying that if the user went from:-

“state0” > “state1” then you DO want to show the header button?
“state2” > “state1” then you DON’T want to show the header button?


#6

Yeah! thats correct @jawache


#7

Hmm i think the best solution might just be to listen to the $stateChangeSuccess event and store the old statename on $rootScope (or if storing data on $rootScope is too ugly for you then whereever and however you prefer to share data).

$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
  $rootScope.model.oldState = fromState.name;
});

And then you could just ng-hide the buttons if the old state is not state0

<ion-nav-buttons side=“secondary ng-hide” ng-hide="model.oldState != 'state0'">
	<button class=“button button-clear”>NewButton
	</button >
</ion-nav-buttons >

A good trick when having conditional buttons in the header is to by default have the ng-hide class, so it by default shows hidden and is only shown the ng-hide resolves to false. Otherwise if ng-hide resolves to true the end user will get a flash of initially seeing the button then it disappearing when angular adds the ng-hide class.