当通过Factory填充$ scope.events时,Angular UI-Calendar AddEvent不起作用

时间:2015-02-04 16:59:13

标签: angularjs fullcalendar angular-ui

如此plunkr示例所示,当事件直接附加到$ scope.events时,可以添加并显示新事件。但是,如果我通过factory.events更新$ scope.events,则新事件不会显示在日历上。

http://plnkr.co/edit/BkdzJJ?p=preview

这一定非常简单,我不知道,但我已经在这个问题上苦苦挣扎数周了。你能帮忙吗?

app = angular.module('myApp');

function CalendarCtrl ($scope, gDataService) {
var today = new Date();
var m = today.getMonth();
var y = today.getFullYear();
var date = new Date();
var d = date.getDate();

$scope.events2 = [];  // This gets data through gDataService
$scope.events3 = [];  // This gets data directly from addEvent_direct method in this controller

// This is how I attempted to populate $scope.events2
$scope.$on('gDataUpdated', function(){
  //alert(gDataService.events2.length);

  $scope.events2 = gDataService.events2;
  alert('gDataService # of events =' + gDataService.events2.length.toString() 
  + '; $scope.events2 includes '+ $scope.events2.length.toString());
  // The alert message indicates $scope.events is properly updated based on 
  // gDataService.events2, but the new event doesn't appear on the calendar.
});

// This is how $scope.events3 is successfully populated
$scope.addEvent_direct = function() {

    var today = new Date();
    var m = today.getMonth();
    var y = today.getFullYear();
    var d = today.getDate();
    object = { title: 'Event directly added',
        start: new Date(y, m, 28),
        end: new Date(y, m, 29),
        className: ['openSesame']}
    $scope.events3.push(object);
}

// both events2 and events3 are included as eventSources
$scope.eventSources = [ $scope.events2 ,$scope.events3];

$scope.uiConfig = {
    fullCalendar: {
        height: 550,
        editable: false
    }
};
}
CalendarCtrl.$inject = [ '$scope','gDataService'];

//这是从另一个控制器(ButtonCtrl)获取event2数据的工厂

app.factory("gDataService", function ($rootScope) {
var service = {};
service.events = [];
service.events2 = [];
service.added_event_short = {start: null, title: null};

service.addData = function(object) {

  this.events2.push(object);
  //alert(this.events2.length);
  $rootScope.$broadcast("gDataUpdated");
};

return service;
});

//这是一个与CalendarCtrl分开的控制器,用于测试不同控制器如何通过工厂

共享数据
app.controller('ButtonCtrl', function($scope,gDataService) {

  $scope.addEvent = function() {

    var today = new Date();
    var m = today.getMonth();
    var y = today.getFullYear();
    var d = today.getDate();
    object = { title: 'Open Sesame',
        start: new Date(y, m, 28),
        end: new Date(y, m, 29),
        className: ['openSesame']}

  gDataService.addData(object);
}
});

1 个答案:

答案 0 :(得分:0)

使用此:

  //$scope.events2 = gDataService.events2; //replace with below
  angular.forEach(gDataService.events2, function(event) {
    console.log(event);
    $scope.events2.push(event);
  });

原因是,你使用' $ scope.events2'绑定视图中的数据,但在更新期间用新数据替换js对象。那么先前物体上的手表不起作用。