简体   繁体   English

如何防止$ watch内部的价值变化

[英]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. 我想确保newValue始终是一个数字,如果不是,请保留oldValue,直到用户键入正确的数字值。

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: 我会写$watch像:

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

    $scope.count=oldValue;
  }
});

Demo Plunker 演示Plunker

One thing with the solution by @Maxim is that it needs the model to be hardcoded. @Maxim解决方案的一个方面是它需要对模型进行硬编码。 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" 使用“this.exp”查找模型名称
  • store the oldValue directly to the model on the scope 将oldValue直接存储到作用域上的模型中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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