gpt4 book ai didi

AngularJS 如何向返回日期的函数添加 +1

转载 作者:行者123 更新时间:2023-12-01 04:43:19 24 4
gpt4 key购买 nike

我有一个表格,标题中有 5 个单元格,每个单元格对应一个星期(例如:第 01 周、第 02 周等等)。

在第一个单元格中,周是这样给出的:

<div class="monthCells">Week {{vm.selectedPeriod}}</div>

结果是标题单元格中的文本:“Week 01”。

Controller 中显示周数的代码是:
return moment.utc(this.date).format("WW");

它始终返回所选月份的第一周的编号,
用户可以使用日期选择器逐月浏览,并在表格中显示该月的周数。

显示其他 4 周的最佳方式是什么?
因为我只得到了第一周的数字,那我在其他 4 个单元格中放什么?

我在考虑一个计数器,所以它在我得到的数字上加了 +1:
return moment.utc(this.date).format("WW");

但问题是,这不会在 ng-repeat 中,但表头是静态的,所以我正在考虑的一个解决方案是在 5 个标题单元格中放置类似的内容:
{{vm.selectedPeriod}}
{{vm.selectedPeriod +1}}
{{vm.selectedPeriod +2}}
{{vm.selectedPeriod +3}}
{{vm.selectedPeriod +4}}

因此,当用户切换月份时,每周的数字都是正确的,但它不起作用,因为我从我的函数中获取了一个字符串,但无法弄清楚如何在该函数中使用 momentJS 解析它。

如果有人对我的想法有解决方案,或者有更好的方法来实现这一点,请告诉我

编辑解决方案:

最后我找到了一个只使用momentJS的解决方案。
{{vm.date | amDateFormat : 'WW'}} 
{{vm.date | amAdd : '1' : 'w' | amDateFormat : 'WW'}}
{{vm.date | amAdd : '2' : 'w' | amDateFormat : 'WW'}}

最佳答案

我会用一个简单而智能的过滤器来做到这一点,就像我在这个 中创建的那样>> Demo fiddle :

看法

<div ng-controller="MyCtrl">
<div class="monthCells">Week {{currentDate|dateWeekFilter:0}}</div>
<div class="monthCells">Week {{currentDate|dateWeekFilter:1}}</div>
<div class="monthCells">Week {{currentDate|dateWeekFilter:2}}</div>
<div class="monthCells">Week {{currentDate|dateWeekFilter:3}}</div>
</div>

AngularJS 应用
var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
$scope.currentDate = moment.utc();
});

myApp.filter('dateWeekFilter', function () {
return function (date, weeksToAdd) {
return moment(date).add(weeksToAdd, 'w').format("WW");
}
});

完整的解决方案,包括: selectedPeriod范围和日期选择器

>> Demo fiddle :

看法
<div ng-controller="MyCtrl">
<datepicker>
<input ng-model="datePickerDate" ng-change="dateChanged()" type="text"/>
</datepicker>
<div class="monthCells">Week {{currentDate|dateWeekFilter:selectedPeriod}}</div>
<div class="monthCells">Week {{currentDate|dateWeekFilter:selectedPeriod+1}}</div>
<div class="monthCells">Week {{currentDate|dateWeekFilter:selectedPeriod+2}}</div>
<div class="monthCells">Week {{currentDate|dateWeekFilter:selectedPeriod+3}}</div>
</div>

AngularJS 应用
var myApp = angular.module('myApp',['720kb.datepicker']);

myApp.controller('MyCtrl', function ($scope) {

//Init
$scope.currentDate = moment.utc();
$scope.datePickerDate = $scope.currentDate.toDate();
$scope.selectedPeriod = 0;

//date change handling
$scope.dateChanged = function () {
$scope.currentDate = moment.utc($scope.datePickerDate);
}

});

myApp.filter('dateWeekFilter', function () {
return function (date, weeksToAdd) {
return moment(date).add(weeksToAdd, 'w').format("WW");
}
});

关于AngularJS 如何向返回日期的函数添加 +1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48863792/

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