0

我已经定义了一个这样的指令:

angular.module('MyModule', [])
    .directive('datePicker', function($filter) {
        return {
            require: 'ngModel',
            link: function(scope, elem, attrs, ctrl) {
                ctrl.$formatters.unshift(function(modelValue) {
                    console.log('formatting',modelValue,scope,elem,attrs,ctrl);
                    return $filter('date')(modelValue, 'MM/dd/yyyy');
                });
                ctrl.$parsers.unshift(function(viewValue) {
                    console.log('parsing',viewValue);
                    var date = new Date(viewValue);
                    return isNaN(date) ? '' : date;
                });
            }
        }
    });

每次我在我的文本框中键入一个键时,解析器似乎都会触发 - 默认事件到底是什么,是它keyup,还是input?以及如何将其更改为仅开火onchange?真的没有必要再经常开火了。

此外,我实际上是在使用 jQuery UI 的 datepicker 操作这个输入的内容。单击日历时,它似乎不会触发导致模型更新/解析器被触发的适当事件。我 我可以强制触发一个事件,但我需要知道是哪一个。


尝试使用scope.$apply(),但这似乎无济于事:

.directive('datepicker', function($filter) {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            $(elem).datepicker({
                onSelect: function(dateText, inst) {
                    console.log(dateText, inst);
                    scope.$apply();
                }
            });
            ctrl.$formatters.unshift(function(modelValue) {
                console.log('formatting',modelValue);
                return $filter('date')(modelValue, attrs.datePicker || 'MM/dd/yyyy');
            });
            ctrl.$parsers.unshift(function(viewValue) {
                console.log('parsing',viewValue);
                return new Date(viewValue);
            });
        }
    }
})

我不认为这里给出的解决方案对我有用,因为(a)我想使用 datepicker 属性值来选择日期格式或其他选项,但更重要的是,(b)它似乎将一个字符串传回当我想要一个实际的日期对象时的模型......所以必须完成某种形式的解析并将其应用于ng-model.

4

1 回答 1

2

在这里,我创建了一个 mo-change-proxy 指令,它与 ng-model 一起使用,它仅在更改时更新代理变量。

在这个演示中,我什至包含了改进的日期输入指令。看一看。
演示: http ://plnkr.co/edit/DBs4jX9alyCZXt3LaLnF?p=preview

angModule.directive('moChangeProxy', function ($parse) {
    return {
        require:'^ngModel',
        restrict:'A',
        link:function (scope, elm, attrs, ctrl) {
            var proxyExp = attrs.moChangeProxy;
            var modelExp = attrs.ngModel;
            scope.$watch(proxyExp, function (nVal) {
                if (nVal != ctrl.$modelValue)
                    $parse(modelExp).assign(scope, nVal);
            });
            elm.bind('blur', function () {
                var proxyVal = scope.$eval(proxyExp);
                if(ctrl.$modelValue != proxyVal) {
                    scope.$apply(function(){
                        $parse(proxyExp).assign(scope, ctrl.$modelValue);
                    });
                }
            });
        }
    };
});
于 2013-01-25T10:10:46.280 回答