angularjs - Dynamically attaching validation in directive does not update class -


i'm trying dynamically toggle validation in form attaching validation directive element under conditions. works intended, input field either valid or invalid depending if directive attached or not , valid. however, when add or remove directive, input field looses it's $dirty , $touched. have ng-class directive in there should change class depending on validity , not work.

the input field looks this, validatelogic function returns true or false.

<input     name="testinput"     type="text"    ng-class="{'error': testform.testinput.$invalid && testform.testinput.$dirty }"    ng-model="testinput"     attach-directive="{'validate-test': validatelogic() }"  /> 

and directive looks this:

myapp.directive('attachdirective', function($compile, $timeout) { return {     restrict: 'a',     require: 'ngmodel',     link: function (scope, element, attrs, ctrl) {         scope.$watch(attrs.attachdirective, attachwatchaction, true);          function attachwatchaction(newvalue) {             angular.foreach(newvalue, function (value, key) {                 if (value) {                     if (!element.attr(key)) {                         var inputval    = element.val();                         element.attr(key, true);                         $compile(element)(scope);                          $timeout(function () {                             element.val(inputval);                             scope.$apply();                         }, 0);                     }                 } else {                     if (element.attr(key)) {                         element.removeattr(key);                         $compile(element)(scope);                     }                 }             });         }     } }; }); 

fiddle: http://jsfiddle.net/oligustafsson/f1wooqd5/

input should read "test" validate

removing attach directive , have validate directive works.

any ideas?

to answer own question, in validation set $dirty:

ctrl.$formatters.unshift(function (value) {     var valid = value === 'test';     ctrl.$setvalidity('validatetest', valid);      if(!valid && value !== '') {         ctrl.$dirty = true;         ctrl.$pristine = false;         ctrl.$touched = true;         ctrl.$untouched = true;     }      return value; }); 

fiddle: http://jsfiddle.net/oligustafsson/10gfnpe2/


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -