3

I have an Onsen-UI Switch. I switch it on, then navigate away from the page. When I return to the page, the switch has changed to off; the switch has not remembered it's state? I am also having trouble coding the Switch so it calls a function on Switch changed. I've read the Onsen Docs and searched online, but I cannot find a clearly coded example to achieve the above.

<label class="switch">
    <input type="checkbox" var="switchName" ng-model="switchState" ng-change="switchChanged()" class="switch__input">
    <div class="switch__toggle"></div>
</label>

Script

function switchChanged() {
     if ($scope.switchState == true) {
            // Switch to saving app data into Production Database
       } else {
            // Switch to saving app data into Developer Database
          };
      };

Thank you for any help.

JaseT
  • 73
  • 5

2 Answers2

2

ons-switch remembers its state as long as the page that contains it is not destroyed and created again. You can achieve that with pushPage in ons-navigator or with persistent tabs in ons-tabbar.

If you want to listen to ons-switch's change event:

document.addEventListener('change', function(event) {
  console.log('Switch value is: ', event.target.checked);
});

You can see it working here: http://codepen.io/frankdiox/pen/JGYZvx

Hope it helps!

Fran Dios
  • 3,482
  • 2
  • 15
  • 26
  • Can `pushPage` be used on a menu choice (e.g. "settings") within an `ons-sliding-menu` ? – JaseT Dec 15 '15 at 12:10
  • it can, pushPage just add page on top of each other. – Gatsbill Dec 15 '15 at 13:29
  • @JaseT Yes, as Gatsbill says, just call `myNavigator.pushPage` from your menu instead of using `myMenu.setMainPage`. – Fran Dios Dec 16 '15 at 00:36
  • I called `myNavigator.pushPage` from the menu and it overwrote the menu, leaving the mainPage unchanged...woops. I tried moving the `ons-navigator` tags to my "settings" page template instead, but didn't work. @Fran I saw your codepen example of pushPage with Sliding-menu in another post, but that seemed to be pushing a page from a link already on the MainPage; I'm trying to push directly from the menu. – JaseT Dec 16 '15 at 04:35
  • 1
    @JaseT You just need to make sure that the parent component in the project is the Sliding Menu. Then make its main page to be a Navigator component. After that you can push pages to that navigator while maintaining the sliding menu always there (navigator changes its content/childs, not its parent). – Fran Dios Dec 16 '15 at 04:42
0

You need to store the state or value ng-nodal (maybe in database). then use that value to initialise your switch input. INITIALISING FROM YOUR STORAGE Controller

$scope.switchtoggle = value == 1;

$scope.switchTrigger = function (obj){
    if(obj){
        //Do something
    } else {
        //Do something else
    }
}

in your HTML

<ons-switch ng-model="switchtoggle" ng-change="switchTrigger(switchtoggle)" ></ons-switch>
shapiro yaacov
  • 2,308
  • 2
  • 26
  • 39