javascriptangularjscheckboxangularjs-nvd3-directives

require confirmation before updating ng-model or executing ng-change in angularjs checkbox input


I have a checkbox input that when checked sets customer.isCompleted to true or false and saves the customer data through a firebase api using ng-change

input type="checkbox" ng-model="customer.isCompleted" ng-change="sc.data.$save(customer)"

however i want to make sure when customer checks the box, it prompts for confirmation. If users hits OK then, it should check the box, update the ngModel and fire ngChangeotherwise do nothing.(and do this when the box is checked or unchecked). when checked the confirmation box should say message1 and when unchecked it should say message2.

how can I implement this. I'm assuming a directive, but don't know how i'd implement it.


Solution

  • After several trial & error i've figured out the code that works. I've expanded upon the $parsers solution from karaxuna. What I'm doing here is checking the $viewValue & $modelValue, correcting viewValue when cancel button is pressed.

     return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
    
        var x = false;
    
        ngModel.$parsers.push(function(val) {
          if (ngModel.$viewValue === true && ngModel.$modelValue === false) {
            if (val && confirm('sure want to check?')) {
              return val;
            } else {
              ngModel.$setViewValue(x);
              ngModel.$render();
              return x;
            }
          }
    
          if (ngModel.$viewValue === false && ngModel.$modelValue === true) {
            if (!val && confirm('sure want to uncheck?')) {
              return val;
            } else {
              ngModel.$setViewValue(!x);
              ngModel.$render();
              return !x;
            }
          }
    
        });
    
      }
    };