观察 ngModel.$invalid 在 angular 指令中的变化 [英] watching for changes in ngModel.$invalid in angular directive

查看:34
本文介绍了观察 ngModel.$invalid 在 angular 指令中的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用自定义输入控件替换 select 元素的指令.这是它的简化版本:

I have a directive which replaces a select element with a custom input control. Here's a simplified version of it:

angular.module('MyModule', []).directive('reflector', function($timeout) {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            element.insertAfter('<input type=text id="new-' + attrs.id + '" />');
            element.hide()
        }
    };

});

我希望这个自定义输入控件能够反映原始选择元素的有效/无效状态,即在基本元素无效时添加 ng-invalid 类.

I'd like this custom input control to reflect the valid/invalid state of the original select element, i.e. add the ng-invalid class when the base element is invalid.

有什么方法可以监视 ngModel.$invalid 的变化吗?我知道我可以做 scope.$watch(attrs.ngModel, ...),但这给了我模型数据,而不是表单元素的有效/无效状态..

Is there any way to watch for changes to ngModel.$invalid? I know I can do scope.$watch(attrs.ngModel, ...), but that gives me the model data, not the form element's valid/invalid state..

推荐答案

您可以从 ngModelController:

$scope.$watch(function(){return ngModel.$invalid;},function(newVal,oldVal){ ...

并且 ngModel 将以下 css 类设置到元素上:ng-valid、ng-invalid、ng-dirty、ng-pristine.

And ngModel sets the following css classes onto the element: ng-valid, ng-invalid, ng-dirty, ng-pristine.

这篇关于观察 ngModel.$invalid 在 angular 指令中的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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