2015-09-07 36 views
0

我在AngularJS應用程序中使用Restangular,但遇到了CRUD操作的一些問題。列表中的Restangular CRUD元素方法

我在嘗試修補並從列表中刪除項目。無論我做什麼,這些錯誤不斷出現:

TypeError: item.remove is not a function at Scope.$scope.deleteItem

TypeError: item.patch is not a function at Scope.$scope.requestItems.Restangular.all.customGET.then.$scope.patchTitleChange

這是我的代碼塊:

appModule 
.controller('AppController', ['$scope', 'Restangular', '$rootScope', '$state', '$document', 
    function ($scope, Restangular, $rootScope, $state, $document) { 
     $scope.items = []; 
     $scope.requestItems = function (search_input, page, status) { 
      var request_params = { 
       "search": search_input, 
       "page": page, 
       "filter_status": status 
      }; 
      Restangular.all('/myUrl/3/').customGET("items", request_params).then(
       function (data) { 
        if (request_params.page == 1) 
         $scope.items = data.results; 
        else 
         $scope.items = $scope.items.concat(data.results); 
        $scope.metadata = { 
         "count": data.count, 
         "next": data.next, 
         "previous": data.previous 
        }; 

        $scope.patchTitleChange = function (index) { 
         console.log($scope.items[index].name); 
         $scope.items[index].patch({name: $scope.items[index].name}); 
        }; 
        $scope.patchDescriptionChange = function (index) { 
         $scope.items[index].patch({description: $scope.items[index].description}); 
        }; 
       } 
      ) 
     }; 
     $scope.deleteItem = function (item) { 
      item.remove().then(function() { 
       var index = $scope.items.indexOf(item); 
       if (index > -1) 
        $scope.items.splice(index, 1); 
      }) 
     }; 

我已經看過有關地雷等問題,並嘗試了他們的答案和解決方案,但沒有似乎工作。

回答

1

分配給您的項目數組的元素不是重新調整元素。您正在分配data.results,它們是純JSON對象。爲了有補丁,刪除等等......他們必須通過Restangular.restangularize傳遞或直接從GET /的GetList請求接受:

//Collection 
$scope.items = Restangular.restangularizeCollection(null, data.results, 'myUrl/3/items'); 

//Individual Items 
angular.forEach(data.results, function (item) { 
    $scope.items.push(Restangular.restangularizeElement(null, item, 'myUrl/3/items'); 
}); 

當restangularizing集合,各個項目也將restangularized,我只提到迭代結果集,因爲它看起來像是追加上面多個調用的結果。

請參閱:Restangular Methods

+0

謝謝,這是問題所在 –