I'm currently trying to work out how to delete a record using Angular JS and Sinatra. At present the code throws an internal 500 server error. I've looked around online for tutorials of how to do this correctly but couldn't find anything that relevant.
My code is as follows below:
app.rb
#Delete download
#not working...
delete '/view1/downloaddelete' do
ng_params = JSON.parse(request.body.read)
@download = Download.get(ng_params)
if @download.destroy
{:success => "ok"}.to_json
#log to console if download delete is successful
puts "download delete successful"
else
halt 500
#log to console if download delete is unsuccessful
puts "download delete unsuccessful halt 500"
end
end
downloads.html
<p>Manage downloads</p>
<ul>
<li ng-repeat="item in items">Title: {{item.title}}, ID: {{item.downloadID}}<a ng-controller="MyCtrl3" ng-click="deletedownload({{item.downloadID}})">Delete</a></li>
</ul>
controllers.js
//not working...
app.controller('MyCtrl3', ['$scope', '$http', function ($scope, $http) {
$scope.downloaddeleteid = {};
$scope.deletedownload = function() {
$http({
method : 'DELETE',
url : '/view1/downloaddelete',
data : $scope.downloaddeleteid
});
}
console.log($scope.deletedownload);
}]);
Any help would be much appreciated please.
You don't need a second controller to do this (MyCtrl3).
Change your link to:
<a ng-click="deletedownload(item.downloadID)">Delete</a>
and add this function to the $scope that this view binds to (the $scope that has the "items" list):
$scope.deletedownload = function(downloadID) {
$http({
method : 'DELETE',
url : '/view1/downloaddelete',
data : downloadID
});
}
Small tutorial:
Your view is associated with a specific $scope which you manipulate from the controller code. There, you define your "items" list and "deletedownload" function. For each item in the list, ng-repeat creates a new $scope that prototypally inherits from the parent $scope (the one mentioned before) all it's properties, plus it defines a new property called "item" which is one item from the list at the time.
When you write:
ng-click="deletedownload(item.downloadID)"
you essentially define a kind of "expression" which evaluates against the associated $scope. This means that the variables you can refer to (the lexical scope) must be properties of the $scope that the anchor DOM element is associated with. Since the anchor element is a child of the list item element, it is associated with the $scope created there. This $scope has a "deletedownload" member inherited from it's parent $scope and an "item" member created by ng-repeat.
I suggest you use Firefox with Firebug + AngScope (a tiny extension i wrote) to inspect $scopes behind DOM elements. You should also verify that HTTP calls to you backend contain the correct data.