我有一个显示datetimepicker的元素。这是时区敏感的。时间存储在作为item
的范围内的item.time
对象中,而TZ则存储为item.timezone
。
我创建了一个指令来渲染它。为了实际正确呈现,它需要知道时区,但是在链接时(当它全部被处理时),控制器还没有正确加载项......或者我认为,但它已正确加载{{ 1}},因为item
就在那里。尽管如此,当格式化程序被调用时,即使item.time
被正确加载,它也会attrs.timezone
为"&#34 ;.
HTML:
modelValue
和JS,(遗漏了大部分......)
<span datetimepicker="true" ng-model="item.time" timezone="{{item.timezone}}"></span>
编辑:
angular正确地评估了attr&#34; timezone&#34;在元素上;它只是在链接功能,甚至格式化程序中都不可用。这是加载后的html:
.directive('datetimepicker',function () {
return {
restrict: 'A',
require: 'ngModel',
template: '<span><input readonly="readonly"></input><span class="glyphicon glyphicon-calendar"></span></span>',
replace: true,
link: function ($scope,element,attrs,ngModel) {
var format = "YYYY-MM-DD H:mm",
formatter = function (modelValue) {
// HERE IS MY PROBLEM: at this point, modelValue does == item.time, but attrs.timezone is "", even though I know it loads correctly!
var ret = modelValue ? moment(modelValue) : "", mtz;
if (ret.tz) {
mtz = ret.tz(attrs.timezone);
}
if (mtz) {
ret = mtz.format(format);
} else if (ret.format) {
ret = ret.format(format);
}
return ret;
};
ngModel.$formatters.push(formatter);
};
})
编辑:添加控制器,高度简化
<span timezone="America/Winnipeg" ng-model="item.time" datetimepicker="true" class="ng-valid ng-valid-datetime ng-dirty">
<input readonly="readonly"/><span class="glyphicon glyphicon-calendar">
</span>
答案 0 :(得分:0)
我认为您应该使用隔离范围,通过属性绑定(=绑定)绑定范围var,并使用scope.$watch
通过回调设置时区:
// directive scope binding
scope: {
timezone: '='
}
// watch local scope var in the link function since it's now binded
scope.$watch('timezone',function(newval, oldval){
// do what you need to do from here when the timezone var gets set
mtz = ret.tz(attrs.timezone);
});