Global 'toggle' variables


#1

Hello!

I have a bit of a problem on my app. Basically I want to implement a global variable that is toggled between true and false when a button in the navbar is clicked. Not only this, but I want the navbar colour to change depending on whether the variable is true or false (and to stay that way when switching views).

I am using the seed project and have created a service to get and set the variable:

.factory('ToggleService', function() {
var toggle = false;

return {
	get: function() {
		return toggle;
	},
	switch: function() {
		if(toggle == true) {
			toggle = false;
		} else {
			toggle = true;
		}
	}
}
});

I am completely not sure if this is the best way to go about it, but I was hoping someone could help me out with the best way to do this type of thing in ionic / angularjs, as well as how to make the ion-nav-bar change css depending on this toggle as it’s in the index.html file.

Many thanks for your help,
Ady


#2

Generally speaking, storing global variables across the app in Services as you’ve done is “best practice”.

Unfortunately, there is no built-in mechanism for changing a header color. The header color is determined when you create it with type="bar-positive". Ionic does not listen for any change events on the bar type.

So, you’ll need to implement that yourself. Maybe use

ng-class={ 'yellow : $scope.toggle === true , 'green' : $scope.toggle === false }

#3

Thanks for the reply.
Unfortunately the code you provided didn’t work.

<body ng-app="app" animation="slide-left-right-ios7">
	<ion-nav-bar type="bar bar-app" ng-class="{ 'class1' : $scope.toggle === true , 'class2' : $scope.toggle === false }"></ion-nav-bar>
	<ion-nav-view name="content"></ion-nav-view>
</body>

This is in the main index.html file. I get the feeling that it can’t access the $scope.toggle variable that’s in the controller (when it’s put through the view):

$scope.toggle = ToggleService.get();

$scope.leftButtons = [{ 
	type: 'button-clear',
	content: '<i class="icon ion-eye"></i>',
	tap: function(e) {
		ToggleService.switch();
		$scope.toggle = ToggleService.get();
	}
}]

Am I right in thinking this? Do you know of a way to get it to work?
As I said before, many thanks, I really do appreciate this support.