gpt4 book ai didi

angularjs - ngModelController : update view value after parser executed

转载 作者:行者123 更新时间:2023-12-05 01:29:10 25 4
gpt4 key购买 nike

我有以下指令:

 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计算model值,需要反射(reflect)back view值;但是怎么办?我知道有 ctrl.$render() 方法,但我想它必须在 $parser 执行后运行。以下无效:

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

我怎样才能渲染 View 值?

最佳答案

这是您所期望的吗? :

 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 '';
});
}
};
});

关于angularjs - ngModelController : update view value after parser executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com