ngModelController:解析器执行后更新视图值

时间:2014-09-02 09:38:00

标签: angularjs angularjs-directive

我有以下指令:

 myDirectives.directive('simpleDate', function ($filter, $locale, $timeout) {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, elem, attrs, ctrl) {
            var dateFormat = 'shortDate';

            ctrl.$formatters.unshift(function (modelValue) {
                if (!modelValue) {
                    return '';
                } else {
                    return $filter('date')(modelValue, dateFormat);
                }
            });

            ctrl.$parsers.unshift(function (viewValue) {
                if (!isNaN(viewValue)) {
                    var now = new Date(),
                        year = now.getFullYear(),
                        month = now.getMonth() + 1,
                        day = Number(viewValue),
                        lastDay = (new Date(year, month, 0)).getDate();
                    if (day >= 1 && day <= lastDay) {
                        return '' + year + (month < 10 ? '-0' : '-') + 
                            month + (day < 10 ? '-0' : '-') + day;
                    }
                }

                return '';
            });
        }
    };     
 });

Parser计算模型值,需要反映后视图值;但怎么样?我知道有ctrl。$ render()方法,但我想它必须在$ parser执行后运行。以下没有工作:

$timeout(function () { ctrl.$render(); });

如何渲染视图值?

1 个答案:

答案 0 :(得分:0)

这是你所期望的吗? :

 myDirectives.directive('simpleDate', function ($filter, $locale, $timeout) {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, elem, attrs, ctrl) {
            var dateFormat = 'shortDate';

            ctrl.$formatters.unshift(function (modelValue) {
                if (!modelValue) {
                    return '';
                } else {
                    return $filter('date')(modelValue, dateFormat);
                }
            });

            ctrl.$parsers.unshift(function (viewValue) {
                if (!isNaN(viewValue)) {
                    var now = new Date(),
                        year = now.getFullYear(),
                        month = now.getMonth() + 1,
                        day = Number(viewValue),
                        lastDay = (new Date(year, month, 0)).getDate();
                    if (day >= 1 && day <= lastDay) {
                        var currentValue = '' + year + (month < 10 ? '-0' : '-') + month + (day < 10 ? '-0' : '-') + day;
                        ctrl.$setViewValue(currentValue);
                        ctrl.$render();
                        return currentValue;
                    }
                }

                return '';
            });
        }
    };     
 });