【发布时间】:2016-11-28 19:41:21
【问题描述】:
我有这个可以正常工作的组件。 它进行 utc->local 和 local->utc 转换(应用逻辑需要)。
在模型中,日期始终为UTC,但为了显示,日期需要以当地时间显示,当在UI中更改时,模型将具有UTC转换的日期。
$scope.$watch 按预期工作 - 当用户尝试更改日期时。
唯一的问题是 - 如果用户决定不更改日期,这个 $scope.$watch 将不会被触发,并且不会有任何转换。
在这种情况下我该怎么办?
Angular/TypeScript 组件:
class RsDateTimeController {
value: Date;
displayValue: Date;
static $inject = ["$scope"];
constructor($scope: ng.IScope) {
$scope.$watch(
"$ctrl.displayValue",
(newValue: Date, oldValue: Date) => {
if (newValue != oldValue) {
this.value = Utility.toUtcDate(newValue);
}
}
);
}
$onInit() {
if (this.value) {
this.displayValue = Utility.toLocalDate(this.value);
}
}
}
class RsDateTimeComponent implements ng.IComponentOptions {
public bindings: any;
public controller: any;
public template: string;
constructor() {
this.template = "<input type='datetime-local' class='form-control' ng-model='$ctrl.displayValue'>";
this.bindings = {
value: "="
};
this.controller = RsDateTimeController;
}
}
HTML:
app.component("rsDatetime", new RsDateTimeComponent());
<div class="form-group">
<label>@("Status Date".T())</label>
<rs-datetime ng-if="vm.woChangeStatus" value="vm.woChangeStatus.StatusDate"></rs-datetime>
</div>
【问题讨论】:
-
您使用的是 Angular 2.0 吗?我问是因为在 2.0 中
$watch不再需要。 -
你为什么不把 this.value 初始化为一些默认值呢?因此,如果用户不更改日期,它将显示默认值。
-
弗里希,角 1.5.хх
-
Hoyen,我愿意,初始化它,但正如我所说,模型中的所有日期值都是 UTC 格式,在 $onInit 中它们将转换为本地时间以进行显示。但是,如果用户不更改该组件中的日期,则不会触发 $scope.$watch,并且本地时间显示的日期将作为本地时间发送到模型,$scope.$watch 内部的转换不会发生。
标签: angularjs typescript