How to prevent value change inside $watch
angularjs
Solution
I would write `$watch` like:
$scope.$watch('count',function(newValue,oldValue)
{
if(newValue !== undefined && !newValue.match(/^[\d]+$/g)){
$scope.count=oldValue;
}
});
Demo Plunker
Problem
I'm $watching a scope value that can be edited by the user in an input field. I want to make sure that newValue is always a number and if it isn't, keep the oldValue until user types in a correct number value. How can I do that? What I'm currently doing is this (inside the link function of a directive): ``` scope.$watch('count',function(newValue,oldValue) { newValue=parseInt(newValue,10); if(isNaN(newValue)) { newValue=oldValue; } }); ``` Is that the proper way of doing that, or is there a better way? Thanks.