Programmatic updating of ion-toggle not working

Hi all, I’ve searched and searched and for the life of me can’t figure out how to programmatically change the value of an ion-toggle.

My toggle starts as on. When someone slides it to off, I popup a confirmation. If they cancel the confirmation, I want to reset the toggle back to on but nothing happens (the console prints out “Clicked Cancel” correctly:

<ion-toggle ng-model="twitterConnection" ng-change="twitterConnectionChange()">Twitter</ion-toggle>

$scope.twitterConnectionChange = function() {
        title: 'Are you sure?',
        template: 'Are you sure you want to disconnect this account?'
    }).then(function(res) {
        if(res) {
            delete $window.localStorage.twitterToken;
            delete $rootScope.user.twitterID;
        else {
            console.log("Clicked No");
            $timeout(function () { $scope.twitterConnection = true; });

Here’s a codepen:


And here’s your solution:


What I changed:

I changed twitterConnection from just a boolean, to an object with the properties “checked” and “text”. You could probably get rid of the text if you don’t need it, but make sure you keep the checked property. Then in your html, you must bind the ng-model to twitterConnection.checked, and set the ng-checked to twitterConnection.checked.

Then in your changeTwitter function, make sure you set the twitterConnection back to true if they click cancel.

It was a little tricky, but what I did to figure out the issue was I took a look at this doc:

And looked at their JS and HTML code to see how they were binding the checked property and noticed you didn’t bind them correctly.

Hope that helps :slight_smile:

1 Like

Amazing, thanks for such a quick reply!

No problem, I’m happy to help :slight_smile: