6

我正在编写一个指令,该指令需要监视使用特定类更新的元素,例如.ng-invalid. 如您所知,.ng-invalid添加到无效的表单元素中。

我需要观察这些元素以确定是添加还是删除了该类。

我怎样才能做到这一点?

提前致谢

4

2 回答 2

6

You could $watch a function that gets the length of $(".ng-invalid"):

scope.$watch(function() {
    return $(".ng-invalid").length;
}, function (newVal, oldVal) {
    if(newVal !== oldVal) {
       console.log('changed!', newVal, oldVal);
       // do your changes here
    }
})

Fiddle. In the fiddle, I added ng-minlength="2" to the first input. Type two characters into that field to see the $watch trigger.

于 2013-04-30T21:01:29.997 回答
1

观察FormController$invalid的属性是否足以满足您的目的?这将通知您表单整体无效状态的更改,例如:

// Somewhere in your directive; formCtrl is the FormController
scope.$watch(function() {
  return formCtrl.$invalid;
}, function(isInvalid, wasInvalid) {
  // ...
});
于 2013-04-30T09:43:01.580 回答