2

我無法實現我的REST資源和AngluarJS日曆控件之間的綁定。看起來我錯過了一些東西,或者只是不要邏輯地得到它,因爲只要有單獨的組件,所有組件都在工作。我用這個Plunker爲例日曆實現:http://plnkr.co/edit/VbYDNK?p=preview如何使用MVP將AngularJS日曆綁定到REST資源

的視圖中:

... 
<div ng-controller="CalendarCtrl" dev-calendar="uiConfig.calendar" class="span8 calendar" ng-model="eventSources" style="padding-top: 30px;"></div> 
... 

控制器內部:

 xyz.controller('MainController', function($scope, $location, $rootScope, MainModel) { 
     ... 
     // REST call - getPendingObjectsByUser 
      $scope.pendingobjects = MainModel.pendingObjectsByUser.get(
        {userId : $rootScope.currentUser.userId}, 
         function(response) {      

          // do something           

        }, function(response) { 

         if(response.status == 404) { 
          $location.path('/notFound'); 
         } else if (response.status == 500) { 
          $location.path('/error'); 
         }  


        }); 
    // this works fine    
    ... 
    function CalendarCtrl($scope) { 

      var date = new Date();var d = date.getDate();var m = date.getMonth();var y = date.getFullYear(); 

       $scope.events = [{type:'birthday', title: 'Brian',start: new Date(y, m, 1)}]; 

       $scope.eventSources = [$scope.events]; 

       $scope.uiConfig = { 
        calendar:{ 
        height: 450, editable: false, defaultView: 'month' 
        } 
       }; 
     } 
// this also works fine 

現在,我試圖做一個簡單的結合,如:

$scope.events = [{title: $scope.pendingobjects.objectsData[0].title , type:'birthday', start: new Date(y, m, 1)}] 

但由於異步行爲其「未定義」。如果我將整個$ scope.events放入可用的響應函數中(如下所示),日曆將不再工作。

// getPendingObjectsByUser 
      $scope.pendingobjects = MainModel.pendingObjectsByUser.get(
        {userId : $rootScope.currentUser.userId}, 
         function(response) {      

          // do something 
          $scope.events = [{type:'birthday', title:'$scope.pendingobjects.objectsData[0].title',start: new Date(y, m, 1)}]                       

}, function(response) { 

         if(response.status == 404) { 
          $location.path('/notFound'); 
         } else if (response.status == 500) { 
          $location.path('/error'); 
         }  

        }) 

我是否需要與承諾一起工作,還是我只是爲了迷惑看到我的錯誤?

回答

1

爲什麼不直接將事件綁定到資源? 像這樣:

$scope.events = function (start, end, callback) { 
    var events = MainModel.pendingObjectsByUser.get({ 
    userId : $rootScope.currentUser.userId 
    }); 

    // Promise 
    events.$promise.then(function (val) { 
      $scope.events = events; 
      callback($scope.events); 
     } 
); 
}; 
     $scope.eventSources = [$scope.events];