0
votes

When I use Ionic toggle with on-change function, it works fine.

<ion-toggle ng-model="pushNotification.checked"
     ng-change="pushNotificationChange()">

After adding ng-true-value and ng-false-value the model is not changed, or at least not in on-change function. It changes within the view however, showing binded value correctly.

<ion-toggle ng-model="emailNotification"
     ng-true-value="'Subscribed'"
     ng-false-value="'Unubscribed'"
     ng-change="emailNotificationChange()">

In controller:

$scope.pushNotificationChange = function() {
  console.log('Push Notification Change', $scope.pushNotification.checked);
};

$scope.emailNotificationChange = function() {
  console.log('Email Notification Change', $scope.emailNotification);
};

Here's the code: https://codepen.io/anon/pen/jqjjZP

Push Notifications toggle logs correctly to the console, while Newsletter toggle always logs 'Subscribed'.

Why?

2

2 Answers

3
votes

This is because ng-model performance 2-way binding only when bound to an object which can be updated via reference. In your case your $scope.pushNotification is an object and that's why it works correct while $scope.emailNotification is a primitive value and doesn't work. Change it to an object and it will work even without the change handler.

<ion-toggle toggle-class="toggle-assertive"
    ng-model="emailNotification.value"
    ng-true-value="'Subscribed'"
    ng-false-value="'Unubscribed'">
  Newsletter
</ion-toggle>


 $scope.emailNotification = { value: 'Subscribed' };

I have created a forked codepen from your code and it works as expected: https://codepen.io/addi90/pen/EKqaOG

0
votes

Well I looked at your code and your ng-model binds directly to ng-true-valueand ng-false-value. So when removing $scope.emailNotification = 'Subscribed'; from the controller the button still works but the logging wil say undefined.

The button will have no value at the start, but will get it when you toggle it.