Toggle a ion-toggle via JavaScript

Hey Guys,
seems to be a simple question, but i can’t figure out how this could be done.

I need a settings menu für my application and i worked with jQuery the whole time so ionic is new to me. I added a ion-toggle to my ion-content and i need the toggle to be activated when the user quits and restarts the application but first activated the option. Therefore i put the ng-change attribute onto my ion-toggle and set a true/false statement into my localStorage (1 and 0).

When my application launches i need to check, whether the state is set to 1 or 0 and if the state is one i need the toggle to look like activated.

How do i achive this?

Many thanks!

okay look at this ionToggle

<ion-toggle ng-model="airplaneMode" toggle-class="toggle-calm">Airplane Mode</ion-toggle>

It is connected with an scope-variable “airplaneMode”.
You can initialize this value in your controller:

$scope.airplaneMode = localStorage.getItem('airplaneMode') === '1' ? 1 : 0;

So if there is the key “airplaneMode” in your localStorage and the value is “1” --> the toggle button gets true/1 and in other cases false/0

1 Like

Thanks, thats so simple and solved my problem. Sorry, but at first all is a bit difficult!

Okay, i thought that this is easy but i don’t know where to place your snippet. I added it into my AppCtrl but it doesn’t change the toggle. It’s deactivated everytime i restart the application although the value in localStorage.airplaneMode is 1.

could you make a codepen with your code?

yes of course http://codepen.io/anon/pen/gaGJBe

next time maybe a full example …

http://play.ionic.io/app/d50d347bbf50

1 Like