AngularJS and ngResouce, what's the magic?-Collection of common programming errors
I’m working currently on RESTful AngularJS $resource feature. I really don’t get all of the feature, even with examples provided by Angular Documentation or Stackoverflow similar subjects.
My usecase is simple :
1) I have a html list, fed with a json file. 2) I change the order via jQuery ui sortable 3) after changing, I would like the server to save the new position of each item of the list.
First and second steps are done : I can read a $resource that looks like this :
function DndCtrl($scope, $resource) {
var feed = $resource('/users/'+ userId +'/test.json');
$scope.tests = feed.query();
}
json file returns items with position and a description.
and display it via html classical Angular call :
When ordering via ui.sortable, I can manage to look at the change with $index+1
But here’s the last step : how to save the change on server after sorting items ?
I tried this basic thing :
function update(index) {
var ch = feed.get({id: index});
ch.position = index+1;
ch.$save();
}
$scope.updateSortable = {
update: function(e, ui) {
update(ui.item.index());
},
placeholder: "xp-hightlight",
axis: 'y'
};
Error I have with this is:
TypeError: Object # has no method 'push'
I probably miss a logical thing somewhere but as I’m not yet at ease with RESTful model, I don’t know exactly what I did wrong 🙂
UPDATE
I just wanted to add a detail about json urls : the read list is available with this route :
/users/:userId/tests (GET)
But each item is available at this route :
/users/:userId/tests/:id (PUT, DELETE)
Of course, in the get method, if I try to catch the second syntax, it returns a 404 Not Found.
SECOND UPDATE :
I tried to modify the call method with this :
function DndCtrl :
var feed = $resource('/users/'+ userId +'/tests/:id', {'update': {method:"PUT", isArray:true}});
and in update function :
var t=$scope.test[index].id;
var ch = feed.get({id:t});
ch.position = index+1;
ch.$update();
It returns :
Uncaught TypeError: Object # has no method '$update' controller.js?body=1:11
GET http://rooturl/users/1/tests/20?update=%5Bobject+Object%5D 404 (Not Found)
Originally posted 2013-12-02 01:41:00.