[英]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. 谢谢。
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.