0
votes

I created a stringToDate directive. The element is wrapped in an ng-repeat directive with a filter. As the filter changes, the element with the directive appears and disappears. When debugging the code, the ngModel contains a $viewValue of NaN, and the $modelValue is undefined. Thus after flipping the filter a few times on the ng-repeat the value is empty. Why is the $parser not called? Am I not handling this correctly? The Date function is from DateJS.

.directive('stringToDate', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function(value) {
                return '' + value;
            });
            ngModel.$formatters.push(function(value) {
                var a = ngModel;
                if(Boolean(value))
                    return Date.parse(value).toString('MM/dd/yyyy');
            });
        }
    };
})
1
Please show the htmlken4z

1 Answers

-1
votes

I'm not sure this is the proper solution, but I added the following to the directive to clean up the parsers. I also call parseAndValidate to return the $viewValue to the $modelValue.

element.on('$destroy', function(){
  ngModel.$$parseAndValidate();
  ngModel.$formatters.pop();
  ngModel.$parsers.pop();
});