AngularJS指令手表有效性 [英] AngularJS directive watch validity

查看:121
本文介绍了AngularJS指令手表有效性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建应[执行某些动作时输入字段被标记为无效指令。对于这个例子让我们假设我有一个指令,它会检查,如果输入的是一个素数,我想创建一个指令,它增加了一个类元素时,它的无效:

I try to create a directive which should peform some actions when an input field is marked as invalid. For this example lets assume I have a directive which checks if the input is a prime number, and I want to create a directive which adds a class to the element when it's invalid:

<input type="text" ng-model="primeNumber" validate-prime invalid-add-class="error">

在验证贷使用在NG-模型解析器和格式化程序来更新模型的有效性。

The validate-prime uses the parsers and formatters on ng-model to update the validity of the model.

现在我想无效相加级指令添加类错误当模特是无效的,而当它是有效的将其删除。换句话说,应该看$模型控制器的有效(或$无效)属性。不过,我可以不知道如何得到这个工作。我想:

Now I want the invalid-add-class directive to add the class "error" when the model is invalid, and to remove it when it is valid. In other words, it should watch the $valid (or $invalid) property of the model controller. However, I can't figure out how to get this working. I tried:

link : function(scope, element, attrs, ctrl) {
    ctrl.$watch("$valid", function(newVal, oldVal) {
    //never fired
    });
}

也许我可以观看范围的一些变量,但我不知道,守候在变。

Perhaps I could watch some variable on scope, but I don't know which variable to watch for.

所以,我怎么能通知时模型更改的有效性?

So how can I be notified when the validity of a model changes?

推荐答案

如果你有一个&LT;形式&GT; ,添加一个名称到它(让我们假设'myForm的')和名称您输入(让我们假设 myInput )。你应该能够 $观看这个是:

If you have a <form>, add a name to it (lets assume 'myForm') and a name to your input (lets assume myInput). You should be able to $watch this by:

scope.$watch('myForm.myInput.$valid', function(validity) {})

如果你没有一个格式,你可以随时观看的功能。通过这种方式:

If you don't have a form, you can always watch a function. This way:

scope.$watch(function() { return ctrl.$valid; }, function(validity){});

您可以阅读更多有关表格的方式这里

You can read more about the form approach here.

这篇关于AngularJS指令手表有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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