不要录制纳克模型无效值 [英] Don't record invalid values with ng-model

查看:106
本文介绍了不要录制纳克模型无效值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢怎么NG-模型属性直接绑定到我的模型和用户得到他们的变化即时反馈。对于我的使用情况下是完美的。不过,我不希望无效值被放入模型中,他们可以抛出一个扳手插入计算。不知何故,我希望模型只更新,如果在表单控件的值是否有效。对于无效的值,它的优良的控制值来改变,而模型值保持固定。

I really like how the ng-model attribute binds directly to my model and users get instant feedback on their changes. For my use case that's perfect. However, I don't want invalid values to be put into the model where they can throw a wrench into the calculations. I somehow want the model to only be updated if the value in the form control is valid. For invalid values, it's fine for the control value to change while the model value stays fixed.

如果我改变角度(1.2rc)的源NgModelController的$ setViewValue实现:

If I change the source of angular (1.2rc) NgModelController's $setViewValue implementation:

this.$setViewValue = function(value) {
...
  if (this.$modelValue !== value) {
    this.$modelValue = value;
    ...
  }
};

要这样:

this.$setViewValue = function(value) {
...
  if (this.$modelValue !== value && this.$valid) {
    this.$modelValue = value;
    ...
  }
};

这似乎做的正是我想要的,但我不知道如何以适当的方式做到这一点。什么是改变这种行为的正确方法?或者,我的努力注定要失败的一些原因?

It seems to do exactly what I want, however I don't know how to do this in a proper way. What's the right way to change this behavior? Or are my attempts doomed to failure for some reason?

更新:新增例如

例如看 http://jsfiddle.net/FJvgK/1/ HTML:

<div ng-controller="MyCtrl">
    {{validNumber}}
    <form>
        <input 
            type="number"
            ng-model="validNumber"
            required
            min="10"
            max="20" 
        />
    </form>
</div>

和JS的:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.validNumber = 15;
}

数目正确显示了10和20之间的值,但我想它,这样,如果你突然键入'8'入禁区,或删除第二位离开1的最后一个有效的数字仍高于显示。也就是说,模型总是有一个有效的值,即使在控制不

The number shows properly for values between 10 and 20, but I want it so that if you suddenly type '8' into the box, or delete the second digit leaving '1' the last valid number still shows above. That is, the model always has a valid value, even if the control does not.

推荐答案

我相信AnugularJS验证器的默认行为不会更新模型,如果传递的值是无效的。如果你看一下开发指南并通过自定义验证这些样品也表明该模型没有更新或者在UI提供的无效值清零

I believe the default behaviour of AnugularJS validators are not to update the model if the value passed is invalid. If you look at the developer guide and go through Custom Validation these samples also show that the model is not update or is cleared on invalid value provided in the UI

这篇关于不要录制纳克模型无效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆