watching for changes in ngModel.$invalid in angular directive

Problem

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

Problem courtesy of: lambinator

Solution

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.

Solution courtesy of: joakimbl

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.