Klyment Klyment - 3 months ago 37
AngularJS Question

How to cancel debounce in ng-model-options in AngularJS

<form name="editForm">
Title<input ng-model="task.title" type="text" name=taskTitle ng-model-options="{ updateOn: 'default' ,debounce{'default':2000000} }">
<a ng-click="UpdateTask(task.title)">SAVE</a>
<a ng-click="editForm.$rollbackViewValue();">DISCARD</a>
</form>


Since the debounce value is very long, when I click "DISCARD", the ng-model will not reflect its changes.

However, what I want is that when I click "SAVE", either I can change the debounce value or make it expired so the changes will be reflected immediately.

I can't find cancelDebounce() in AngularJs document, anyone would like to provide a solution? Thanks

Answer

I'd suggest you to have one scope variable which will have value of debounce like $scope.myDebounce = 2000000, then do create one discard function inside controller that will first reset the be-bounce value to 0, then do rollback the form changes. Reset the myDebounce variable to its actual value in next digest cycle.

Markup

<form name="editForm">
    Title<input ng-model="task.title" type="text" name=taskTitle ng-model-options="{ updateOn: 'default' ,debounce{'default': myDebounce } }">
    <a ng-click="UpdateTask(task.title)">SAVE</a>
    <a ng-click="editForm.$rollbackViewValue();">DISCARD</a>
</form>

Code

$scope.myDebounce = 2000000; //somewhere in controller

$scope.discard = function (form) {
   $scope.myDebounce = 0; //resetting debounce to get quick `ng-model` update
   form.$rollbackViewValue(); 
   $timeout(function(){
       //setting the actual debounce value to old one in next digest
       $scope.myDebounce = 2000000; 
   });
}