I am having a problem with a directive. The purpose of the directive is to easily add validation without having to manually add ng-class (among other things) to elements in order to get the error state to show up. I just simply want to put a "validation" directive on my element and have the appropriate classes (and error messages) be generated when there is an error state.
As far as the validation goes, it is working great, but it causes an odd side effect. Whenever I am editing a value in an input box that has the validation directive on it, it moves the caret to the end of the text in the input field. It appears to be the fact that I'm compiling the element (in this case the parent element which contains this element).
Here is a jsbin showing the problem. To reproduce, type a value in the field, then put the caret in the middle of the value you just typed and try typing another character. Notice it moves you to the end of the field. Notice that if you delete the value, the field label turns red as expected to show a validation error (the field is required).
Here is the directive (from the jsbin):
angular.module('app', [])
.directive('validation', function($compile) {
return {
require: 'ngModel',
restrict: 'A',
compile: function(compileElement, attrs) {
var formName = compileElement[0].form.name;
compileElement.removeAttr('validation');
compileElement.parent().attr('ng-class', formName + "['" + attrs.name + "'].$invalid && " + formName + "['" + attrs.name + "'].$dirty ? 'error' : ''");
return function(scope, element) {
$compile(element.parent())(scope);
}
}
};
});
And here is the html:
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
</head>
<body ng-app="app">
<form name="subscribeForm">
<label>
First Name
<input type="text"
id="firstName"
name="firstName"
ng-model="userInfo.FirstName"
required
validation/>
</label>
</form>
</body>
</html>