i'm making validator validates valid dates mm/yyyy, didn't how access attribute when model changes:
<input id="my-date" validate-short-date data-max-date="{{thismonth}}" type="text" name="mydate" data-ng-model="mymodeldate"> here directive
.directive('validateshortdate', ['moment', function(moment) { return { restrict: 'a', require: 'ngmodel', link: function($scope, element, attr, ngmodel) { var maxdate = false; var pattern, regex; pattern = '^((0[0-9])|(1[0-2])|[1-9])\/(19|20)[0-9]{2}$'; regex = new regexp(pattern, 'i'); if(!angular.isundefined(attr.maxdate)) { // got once maxdate = attr.maxdate; } ngmodel.$validators.maxdate = function(modelvalue) { // maxdate var undefined after first time if (maxdate && regex.test(modelvalue)) { var modeldate = moment(modelvalue, 'mm/yyyy').format('yyyymm'); return modeldate <= maxdate; } return true; }; ngmodel.$validators.valid = function(modelvalue) { return modelvalue === '' || modelvalue === null || angular.isundefined(modelvalue) || regex.test(modelvalue); }; } }; }]) the validator ngmodel.$validators.valid works perfect, inside ngmodel.$validators.maxdate cannot attr.maxdate first time directive fires.
so how can access custom attribute value every time check modelvalue?
i'm not expert angularjs , i'm missing important.
the attrs argument in link function provides $observe method can use attach listener function dynamic changes in attribute value.
it simple use inside of link function:
attr.$observe('maxdate', function() { scope.maxdate = attr.maxdate; ngmodel.$validate(); }); here working plunker
Comments
Post a Comment