quma
quma

Reputation: 5753

Reduce the number of model updates with a color picker

I use a standard HTML color picker in my application:

<input type="color" ng-model="vm.currentUser.color" />

If I click the button of that color picker and manually change the color, then the model is updated very often. Since I have a watch on vm.currentUser.color, the corresponding method is also invoked very often, and that's problematic.

Is there any way to set the model variable only when the OK button of the color picker is clicked?

Image of the color picker

Upvotes: 6

Views: 693

Answers (2)

Blackhole
Blackhole

Reputation: 20411

Since AngularJS 1.3.0-beta.6, there is a ngModelOptions directive, perfectly suited to your problem. It allows you to "tune how model updates are done", which is perfectly what you're looking for.

For instance, you can update the model only if the value doesn't change after a reasonable amount of time. I'll use a value of 500 milliseconds here in order to make the effect really apparent, but in practice, a lower one seems more appropriate.

<input
    type="color"
    ng-model="color"
    ng-model-options="{debounce: 500}"
/>

Example on JSFiddle

Upvotes: 1

Shomz
Shomz

Reputation: 37711

You can use ng-change on that field as it triggers only after the color popup is closed and if a change occurs (no matter how many times you change the color inside the popup): http://plnkr.co/edit/AjDgoaUFky20vNCfu04O?p=preview

angular.module('app', [])
  .controller('Ctrl', function($scope, $timeout) {
    $scope.x = '#ff0000';
    $scope.res = '';
    $scope.a = function(x) {
      console.log(x);
      $scope.res = 'Color changed to ' + x;
      $timeout(function(){$scope.res = ''}, 2000);
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
  <input type="color" ng-model="x" ng-change="a(x)">
  <p>{{res}}</p>
</div>

Upvotes: 2

Related Questions