我有一个像这样定义的AngularJS $资源:
var Menus = $resource('http://cafe.com/api/menus');
和RESTful API。因此,当我在GET
上Menus
时,我得到了回复:
<cafe>
<collection href="http://cafe.com/api/menus" type="menus">
<template>
<data name="Name" prompt="Menu name" />
</template>
<items>
<item href="http://cafe.com/api/menus/1">
<link href="http://cafe.com/api/menus/1/ingredients" rel="ingredients" />
<data name="Name" prompt="Menu name">Morning</data>
</item>
<item href="http://cafe.com/api/menus/2">
<link href="http://cafe.com/api/menus/2/ingredients" rel="ingredients" />
<data name="Name" prompt="Menu name">Happy Hour</data>
</item>
</items>
</collection>
</cafe>
问题,如何删除菜单2? (鉴于它有自己的超媒体链接:http://cafe.com/api/menus/2
)
答案 0 :(得分:11)
假设您已从XML转换为Angular托管的JavaScript对象数组,您可以使用它来呈现对象:
<tr ng-repeat="cafe in cafes">
<td>{{cafe.name}}</td>
<td>
<button class="btn" ng-click="deleteCafe($index, cafe)">Delete</button>
</td>
</tr>
在你的控制器中你可以这样做:
function ListCtrl($scope, $http, CafeService) {
CafeService.list(function (cafes) {
$scope.cafes = cafes;
});
$scope.deleteCafe = function (index, cafe) {
$http.delete(cafe.self).then(function () {
$scope.cafes.splice(index, 1);
}, function () {
// handle error here
});
}
}
看,没有客户端创建的URL! :)
更新:修复了splice命令中的错误,splice(index, index)
,但应为splice(index, 1)
。
答案 1 :(得分:2)
如果您的REST服务将JSON返回到angular,并且JSON在返回的数据中包含菜单ID。
var Menu = $resource('http://cafe.com/api/menus/:id', { id: '@id' }); // replace @id with @<the id field in your json object>
// Delete menu 2
Menu.delete({id: 2}, function(){ // Success callback
// Get all menus,
var menus = Menu.query(function() { // Success callback
// alternative delete syntax:
var lastMenu = menus.pop();
lastMenu.$delete();
});
});