AngularJS中mwl-calendar如何按数据库notifyDate正确展示事件?
解决mwl-calendar事件全部显示在当日的问题
看起来你遇到的核心问题是mwl-calendar(angular-calendar)无法识别你传入的notifyDate字符串作为事件的日期——这个组件要求每个事件对象必须包含start(必填)属性,且该属性是JavaScript的Date类型对象,而不是字符串格式的日期。下面是具体的解决步骤和代码修改方案:
问题原因
mwl-calendar会根据事件对象的start字段(Date类型)来定位事件到对应的日历日期。你当前只传递了notifyDate字符串,组件无法解析这个字段,所以默认将所有事件都放到了当前日期。
解决方案步骤
- 将数据库返回的
notifyDate字符串转换为Date对象; - 给每个事件添加
start属性(组件必需),如果是全天事件,还可以添加allDay: true属性; - 可选:自定义事件显示模板,直接展示
employeeName。
修改后的控制器代码
$scope.myevents = function(start, end, timezone, callback) { SalesNotifyService.getAllNotify().success(function(data) { $scope.events = []; angular.forEach(data,function(event,key){ // 解析DD-MM-YYYY格式的日期字符串(如果你的格式是MM-DD-YYYY,调整拆分顺序即可) const dateSegments = event.notifyDate.split('-'); // JavaScript Date的月份是0-based(0=1月,11=12月),所以要减1 const eventStartDate = new Date(dateSegments[2], dateSegments[1] - 1, dateSegments[0]); $scope.events.push({ start: eventStartDate, // 组件识别的核心日期字段 allDay: true, // 标记为全天事件,会显示在日历的全天区域 employeeName: event.employeeName, // 保留原字段方便后续使用 title: event.employeeName // 可选:如果用默认模板,title会显示事件内容 }); }); callback($scope.events); }); }; // 优化eventSources:只保留myevents函数即可,避免重复加载 $scope.eventSources = [$scope.myevents];
自定义事件显示的HTML代码(可选)
如果你想直接在日历上显示employeeName而不是默认的title,可以添加自定义事件模板:
<mwl-calendar events="events" view="calendarView" current-day="viewDate" view-title="calendarTitle" ng-model="eventSources" cell-is-open="cellIsOpen" day-view-start="06:00" day-view-end="22:59" day-view-split="30" cell-modifier="modifyCell(calendarCell)" cell-auto-open-disabled="true" on-timespan-click="timespanClicked(calendarDate)"> <!-- 自定义事件模板,直接展示employeeName --> <mwl-calendar-event-template> <span class="calendar-event-text">{{event.employeeName}}</span> </mwl-calendar-event-template> </mwl-calendar>
关键注意点
- 日期格式适配:如果你的
notifyDate是MM-DD-YYYY格式,那么创建Date对象时要调整顺序:new Date(dateSegments[2], dateSegments[0] - 1, dateSegments[1]); - 事件字段必填项:
start是mwl-calendar事件的必填字段,必须是Date类型,否则组件无法正确定位事件; - eventSources优化:原来的
eventSources同时包含$scope.events和$scope.myevents可能导致重复加载事件,直接使用$scope.myevents函数即可,组件会在需要时自动调用它获取事件数据。
内容的提问来源于stack exchange,提问作者Sachin HR
相关产品推荐
相关产品推荐

