我需要一个指令来解析用户输入的日期并对其进行验证。所以我写了以下内容:
myDirectives.directive('myDate', function($filter) {
    'use strict';
    return {
        require:'ngModel',
        restrict:'A',
        link:function (scope, elem, attrs, ctrl) {
            var dateFormat = attrs.myDate ? attrs.myDate : 'shortDate';
            ctrl.$formatters.unshift(function(modelValue) {
                return $filter('date')(modelValue, dateFormat);
            });
            ctrl.$parsers.unshift(function(viewValue) {
                var date = new Date(viewValue);
                if (isNaN(date)) {
                    ctrl.$setValidity('date', false);
                    return undefined;
                } else {
                    var dateString = $filter('date')(date, dateFormat);
                    if (dateString !== viewValue) {
                        ctrl.$setViewValue(dateString);
                    }
                    ctrl.$setValidity('date', true);
                    return date;
                }
            });
        }
    };
});
只有在输入失去焦点后才需要进行解析,所以我使用了另一个指令,我在这里找到了。问题是
ctrl.$setViewValue(dateString);
不起作用,因为如 angularjs 文档中所述,必须从 DOM 事件处理程序中调用 setViewValue()。我应该怎么做才能反映解析结果?