简体   繁体   中英

How to prevent value change inside $watch

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;
  }
});
  • added "scope" to the parameters.
  • find the model name using "this.exp"
  • store the oldValue directly to the model on the scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM