How to use setChecked in onsen SwitchView

420 views Asked by At

I have used ons-switchView in my list as follows:

<ons-list-item modifier="item" class="list__item__line-height">
    Switch View <ons-switch modifier="list-item" var="switchView" ng-click='onSwitchViewClick()'></ons-switch>
</ons-list-item>

and in my controller, I want to try something as follows:

if (localStorageService.get('switchView') === 'grid') {
    $scope.switchView.setChecked(true);
}
else {
    $scope.switchView.setChecked(false);
}

However, I got some error stating that error of undefined. I guess something must be wrong here:

$scope.switchView.setChecked(true);

But I cannot get it work. Any help is really appreciated!

1

There are 1 answers

5
Andi Pavllo On

I guess you are trying to access switch, from the controller, before it gets initialized on the DOM, that's why you are getting undefined error.

Here is a working CodePen example. and the relative code.

In your case, the code should be something like(I used a button to check the value, but you can also do it dynamically):

HTML

<div ng-controller="MyController">
  <ons-list-item modifier="item" class="list__item__line-height">
    <ons-switch var="switch"></ons-switch>
    <ons-button ng-click="checkSwitch()">Check switch status</ons-button>
  </ons-list-item>
</div>

Controller

ons.bootstrap()

.controller('MyController', function ($scope) {
  $scope.checkSwitch = function() {
    if(localStorageService.get('switchView') === 'grid') 
      $scope.switch.setChecked(true);
    else
      $scope.switch.setChecked(false);
  };
});