watching for changes in ngModel.$invalid in angular directive

笑着哭i 提交于 2019-12-12 13:34:11

问题


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()
        }
    };

});

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.

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..


回答1:


You can watch all the attributes from the ngModelController:

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

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



来源:https://stackoverflow.com/questions/16925192/watching-for-changes-in-ngmodel-invalid-in-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!