Slow performance of $watch

Issue

I am using angular range slider in my project for having the extended Slider functionality.

I am enclosing the relevant code here.
The directive that I am using has this syntax in the minimal version:

<body ng-controller=“MainController as MC”>
  <div range-slider 
    min="0” 
    max=“MC.maxPrice” 
    pin-handle="min” 
    model-max=“MC.price”
  >
  </div>
</body>

Consider the following code inside the controller:

this.maxPrice = '1000';
this.price = '69’;

$scope.$watch('MC.price', function (newVal) {
  if (newVal || newVal === 0) {
    for (var i = 0; i < 999; i++) {
      console.log('Successful ouput #' + i);
    }
  }
});

This seems to be working. But it runs slow.

Could somebody suggest me some workaround or suggestion to improve the performance?

Solution

I think you can use a temporary model.
You can add a temporary model bound to change the working model on timeout:

<body ng-controller="MainController as MC">
  <div range-slider 
    min="0"
    max="MC.maxPrice"
    pin-handle="min"
    model-max="MC.priceTemporary"
  >
  </div>
</body>

and modify the controller as:

this.maxPrice = '100';
this.price = '55';
this.priceTemporary = '55';

$scope.$watch('MC.price', function (newVal) {
  if (!isNaN(newVal)) {
    for (var i = 0; i < 987; i++) {
      console.log('Successful ouput #' + i);
    }
  }
});

var timeoutInstance;
$scope.$watch('MC.priceTemporary', function (newVal) {
  if (!isNaN(newVal)) {
    if (timeoutInstance) {
      $timeout.cancel(timeoutInstance);
    }

    timeoutInstance = $timeout(function () {
      $scope.MC.price = newVal;
    }, 144);

  }
});

Answered By – user7368531

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published