noli
noli

Reputation: 3745

Ionic - AngularJS : ion-toggle doesn't update the model

I have a strange issue with the ion-toggle directive in Ionic framework.

When using ion-toggle like this :

<ion-toggle ng-model="testToggle">Test toggle</ion-toggle>

JS:

$scope.$watch('testToggle',function(value) {
    console.log('testToggle changed to '+value);
})

The controller doesn't receive any update at all.

Here's the CodePen : http://codepen.io/anon/pen/jPOMqz

You'll see that i've added an $interval that changes a binded variable to random in order to see that everything else works as expected

Thank you very much :)

Upvotes: 2

Views: 13403

Answers (2)

Keval
Keval

Reputation: 3389

I used ng-change to detect a change; and I am calling the function toggleChange() upon a change. So your ion-toggle will look like:

<ion-toggle ng-model="value" ng-change="toggleChange()">Test toggle</ion-toggle>

And your controller will change the $scope.value and hence you'll get the toggle's value from $scope.value:

.controller('ContactCtrl', function($scope, $interval) {
            $scope.value = false;
            console.log('ContactCtrl started');

            $scope.toggleChange = function() {
                if ($scope.value == false) {
                    $scope.value = true;
                } else
                    $scope.value = false;
                console.log('testToggle changed to ' + $scope.value);
            };
        }

Here's the Codepen for the same: http://codepen.io/keval5531/pen/LVYROp

Upvotes: 13

Ishan Thilina Somasiri
Ishan Thilina Somasiri

Reputation: 1244

The answer by Keval didn't work for me because he's resetting the value of the model, which puts the toggle button to its original position. So the proper answer would be to create a toggle like the following.

<ion-toggle ng-model=value ng-change="toggleChange()">Test toggle</ion-toggle>

And then write the controller as follows.

.controller('ContactCtrl', function($scope, $interval) {
        $scope.value = false;

        $scope.toggleChange = function() {
            console.log('testToggle changed to ' + $scope.value);
        };
    }

Upvotes: 0

Related Questions