ng-checked triggers its function more than once

All we need is an easy explanation of the problem, so here it is.

that’s the code in the view :

 <input type="radio" name="tabset" id="tab2" aria-controls="rauchbier"
        ng-checked="switch_tabs()">

and that’s the code in the controller

   $scope.switch_tabs = function(){
        console.log(notification_form_data);
        console.log($('#notification_form').serialize());
        if (notification_form_data != $('#notification_form').serialize() & notification_form_data!= undefined)
        { 
            var alertPopup = $ionicPopup.alert({
            title: 'vs',
            template: 'unsaved data in actions',
            button: 'Done'

        });

    }

the alert and the console.log happens 100 times when the condition = true how to fire it only 1 time

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Why is ng-checked firing twice on page load

ng-checked is meant to be a boolean. So it’s meant to be like ng-checked="checkbox_checked" and that will check the checkbox when checkbox_checked is true for example.

You may want to use ng-click to fire your function once when the radio box is clicked.

Or if you want something to happen when a variable changes you can use $scope.$watch

$scope.$watch('notification_form_data', function() {
   if (notification_form_data != $('#notification_form').serialize() & notification_form_data!= undefined)
    { 
      var alertPopup = $ionicPopup.alert({
      title: 'vs',
      template: 'unsaved data in actions',
      button: 'Done'
     };
})

Or you can add an ng-model and use ng-change which will call your function when the model changes. If you only want the alert to run when the radio box is checked, you can check if the variable used in your ng-model is true.

<input type="radio" name="tabset" id="tab2" aria-controls="rauchbier"
        ng-model="radio_checked" 
        ng-changed="switch_tabs()">
$scope.radio_checked = false
$scope.switch_tabs = function(){
        console.log(notification_form_data);
        console.log($('#notification_form').serialize());
        if (notification_form_data != $('#notification_form').serialize() && notification_form_data!= undefined && $scope.radio_checked)
        { 
            var alertPopup = $ionicPopup.alert({
            title: 'vs',
            template: 'unsaved data in actions',
            button: 'Done'

        });

    }

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply