Reputation: 5753
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?
Upvotes: 6
Views: 693
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}"
/>
Upvotes: 1
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