angularjs - Set ons-switch with predifined values from Angular controller -
i cannot seem correct way set 'checked' attribute in ons-switch. can setup user configurations page pre-checked select boxes.
the docs: checked switch how set using variable in angular controller?
for example, if ons-switch has syntax have done:
i cannot seem set attribute "checked" no value in angular, needed in docs. i'm unable access variable since part of array of configurations.
code example:
controller:
var categinfo = [{interest:'classic', ischecked:true}, {interest:'new', ischecked:false}];
html:
<ons-list-item ng-repeat="interest in categinfo" > <span style="color: #666">{{interest.interest}}</span> <ons-switch modifier="list-item" var="{{interest.interest}}" checked="{{interest.ischecked}}"></ons-switch> </ons-list-item>
so want html should show buttons checked/unchecked depending on interest.ischecked true or false.
first of all, need bind switch ng-model
, allow manage ons-switch
behavior directly controller. setting variable true
or false
, inside controller, automatically change value of state of switch, same thing if change state switch (angularjs binding).
if want check status of switch, need check model value.
here codepen example. , relative code.
html
<div ng-controller="mycontroller"> <ons-switch ng-model="switch"></ons-switch> <ons-button ng-click="changeswitch()">change switch status</ons-button> </div>
controller
ons.bootstrap() .controller('mycontroller', function ($scope) { $scope.changeswitch = function() { $scope.switch = !$scope.switch; if($scope.switch) alert('checked'); else alert('unchecked'); }; });
edit: switch array example
due onsen ui bug initialization of ons-switch
element, suggest use following code implement switch.
<label class="switch"> <input type="checkbox" class="switch__input" checked> <div class="switch__toggle"></div> </label>
the appearance same ons-switch
element. bug fixed in onsen ui 1.4 release, can start using again switch element after release.
for concerns behavior of array of switches, it's analog of single switch. still need use 'ng-model' bind status of switch. using ng-repeat
display switch elements so, using ng-model="item.ischecked"
, every element binded relative ischecked
value inside array. here can find working codepen example, , relative code:
html
<div ng-controller="mycontroller"> <h2>what trying</h2> <div ng-repeat="item in categinfo"> <div>this button should {{item.ischecked}}</div> <label class="switch"> <input ng-model="item.ischecked" type="checkbox" class="switch__input" checked> <div class="switch__toggle"></div> </label> </div> </div>
controller
ons.bootstrap() .controller('mycontroller', function ($scope, $timeout) { //need go through array , set checked or not $scope.categinfo = [{interest:'classic', ischecked:true}, {interest:'new', ischecked:false}]; });
Comments
Post a Comment