Get and set checkbox toggle input state

I’m very new to Ionic and Angular, so I’m having some difficult getting started on very simple concepts. I’m trying to get the value/state of form elements and am having trouble with the checkbox toggles.

Basically, I need to track when a user changes the state, save it to localStorage, and then load use it to load again later - so it remembers their settings.

My toggle code looks like this:

<li class="item item-toggle">
     National Insurance
     <label class="toggle toggle-positive" id="has_ni_toggle" name="has_ni_toggle">
       <input type="checkbox" id="has_national_insurance" name="has_national_insurance" checked="checked">
       <div class="track">
         <div class="handle"></div>
       </div>
     </label>
  </li>

Note: I’m using the HTML and not <ion-toggle> because I’m still learning AngularJS and don’t fully understand the concepts right now.

I really just want the simplest way to grab the current value of the toggle and store it in a variable that I can then use to save to localStorage. Do I need a listener for when the state changes, or what is the best way to go about this?

Thanks!

-Ian

2 Likes

I’m still learning my way around Ionic, but I’d check out the ngChange directive. Instead of defining a listener, you could do something like:

<input type="checkbox" ng-model="myVar" ng-change="updateLocalStorage()" />

Then in your controller in the updateLocalStorage function, you can save $scope.myVar to localStorage. I’d check out this guide on how to use localStorage.

1 Like

Hey Drew!

Thanks for that. I’ve done the following:

$scope.updateLocalStorage = function() {
			window.localStorage.setItem( 'has_national_insurance', $scope.ni_toggle );
			console.log( $scope.ni_toggle );
		}

However, it logs out $scope.ni_toggle as undefined. If I add {{ni_toggle}} to my template, it shows true/false correctly depending on the toggle status, but it doesn’t seem to be updating the value in my controller so I can save it to localStorage and use it again on app load to remember the user settings.

Appreciate your help! I’ll keep digging in to see if I can figure it out :slight_smile:

Hmm, I’d have to see your code to see what’s going on, but it shouldn’t have anything to do with Ionic.

Here’s a codepen if you’re still working on it.

Thanks for the help! It was because I’m using tabs, they create a new scope so I had to set $scope.data to get it working. Here’s the answer I got from Stack Overflow, in case it helps somebody else:

It is a typical issue related to Scope prototypal inheritance (you can read about it in the Angular wiki). Basically, because you use a view and a view creates a new scope, you are binding your ngModel to the view’s scope’s ni_toggle property, but you are updating the localStorage with the SettingsCtrl’s scope’s ni_toggle property (which is never changed from false)

And a plnkr with the working code