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.
I would write $watch
like:
$scope.$watch('count',function(newValue,oldValue)
{
if(newValue !== undefined && !newValue.match(/^[\d]+$/g)){
$scope.count=oldValue;
}
});
Demo Plunker
One thing with the solution by @Maxim is that it needs the model to be hardcoded. It works but an improved solution could look like this:
$scope.$watch('count',function(newValue,oldValue,scope) {
if(newValue !== undefined && !newValue.match(/^[\d]+$/g)){
scope[this.exp] = oldValue;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With