简体   繁体   中英

Updating nested array value when child array is updated with $promise results

I'm building a scheduler app using the FullCalendar component which is fed events from a nested array model $scope.eventSources consisting of multiple child arrays of events (gDataService.events being one of them). It uses $resource inspired by this plunkr example. http://plnkr.co/edit/pIDltQRV6TQGD4KQYnj7?p=preview .

When the following controller first runs, gDataService.events is assigned the function(start, end, callback)... as its value, and $scope.eventSource is assigned an array of 1 element (which is the function). The problem is when the calFactory successfully pulls the data from the server through $resource, gDataService.events is properly populated with event data, but $scope.eventSource doesn't (ie. still keeps the old value of 1 function element). I tried $scope.$apply, but it complains that digest is already in progress.

Your help is much appreciated.

myApp.controller("MainCtrl", function($scope,$compile,uiCalendarConfig, calFactory, gDataService)     {

var getEventSuccessCallback = function (data, status) {
    gDataService.events = function(start, end, callback) {
        var events;
        events = data.query({
          start: start,
          end: end
        });

        events.$promise.then(function(value){
           gDataService.events = value ;
          callback(gDataService.events);
    };

    $scope.eventSources = [gDataService.events];

};
})
myApp.factory("calFactory",['$resource', function($resource) {
    return {
        getEvents: function () {
            return $resource("/caldata/?c=to1_list",{});
    }
};
}]);

The reason is that $scope.eventSources = [gDataService.events]; is defined within the function and should be defined in the controller, outside of the function. Try this:

myApp.controller("MainCtrl", function($scope,$compile,uiCalendarConfig, calFactory, gDataService) {

    var getEventSuccessCallback = function (data, status) {
        gDataService.events = function(start, end, callback) {
            var events;
            events = data.query({
               start: start,
               end: end
            });

            events.$promise.then(function(value){
               gDataService.events = value ;
              callback(gDataService.events);
            };
     };

     $scope.eventSources = [gDataService.events];
});

It seems you have a bracket issue there, since I see you also define a factory inside a controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM