0

I'm using an old version of timepicker, which lacks the min & max options (and which I sadly can't update at this time). My view looks like this:

 <timepicker class="col-md-2" ng-model="date" hour-step="1" minute-Step="0">

I want to prevent timepicker from increasing/decreasing the time beyond certain values. I currently use a watch:

retyped instead of copy-paste, so obvious syntax errors are likely typos, sorry

$scope.$watch('date', function(newVal, oldVal){
     if(newVal<minTime){
         $scope.date=minTime
         $scope.digest();
     }

     else if(newVal>maxTime){
         $scope.date=maxTime
         Rscope.digest();
     }
}

I needed the digests or the timePicker wouldn't reflect my adjusting the time back to my desired values. However, I now can get a "$digest already in progress" error per this question: AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

However, it's also stated that this is considered an undesirable approach, and that it would be better to avoid using $watch if at all possible.

Is there a different approach beyond the $watch & $digest approach I'm using to more elegantly prevent/reset scope changes like this, that ensures that the timepicker will immediately reflect my reverting it's changes?

...yes switching away from the timepicker were using is already on the to-do list, there are other reasons I dislike it, but I'm more interested in how to handle this use case in general then a fix to this specific issue.

Community
  • 1
  • 1
dsollen
  • 6,046
  • 6
  • 43
  • 84

1 Answers1

1

You need to update your model in setTimout() like below to avoid the error $digest already in progress

setTimeout(function () {
                    scope.$apply(function () {
                        scope.location3 = 'Your selected value'
                    });
}, 2000);

Alternatively you can also utilize $timeout service to achieve the same result.

Rishi Tiwari
  • 1,041
  • 1
  • 10
  • 20