Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent value change inside $watch

Tags:

angularjs

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.

like image 458
Francisc Avatar asked Nov 22 '13 14:11

Francisc


2 Answers

I would write $watch like:

 $scope.$watch('count',function(newValue,oldValue)
{
  if(newValue !== undefined && !newValue.match(/^[\d]+$/g)){

    $scope.count=oldValue;
  }
});

Demo Plunker

like image 113
Maxim Shoustin Avatar answered Nov 10 '22 03:11

Maxim Shoustin


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;
  }
});
  • added "scope" to the parameters.
  • find the model name using "this.exp"
  • store the oldValue directly to the model on the scope
like image 2
Netsi1964 Avatar answered Nov 10 '22 04:11

Netsi1964