I'm using Restangular with an AngularJS app, but am experiencing some problems with CRUD operations.
I'm trying to patch and remove items from a list. No matter what I do, these errors keep appearing:
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
This is my code block:
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);
})
};
I have looked at other problems related to mine and tried out their answers and solutions, but nothing seems to work.
The elements assigned to your items array are not restangularized elements. You are assigning data.results which are plain JSON objects. In order to have patch, remove, etc... they must be passed through Restangular.restangularize or be directly received from get / getList requests:
//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');
});
When restangularizing a collection, the individual items will also be restangularized, I only mention iterating over the result set because it appears you are appending the results from multiple calls above.
See: Restangular Methods