AngularJS $资源和超媒体

Gre*_*reg 7 javascript rest hypermedia angularjs

我有一个像这样定义的AngularJS $资源:

var Menus = $resource('http://cafe.com/api/menus');
Run Code Online (Sandbox Code Playgroud)

和一个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>
Run Code Online (Sandbox Code Playgroud)

问题是,如何删除菜单2?(因为它有自己的超媒体链接:http://cafe.com/api/menus/2)

Try*_*tøl 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>
Run Code Online (Sandbox Code Playgroud)

在你的控制器中你可以这样做:

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
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

看,没有客户端创建的URL!:)

更新:修复了splice命令中的错误splice(index, index),但是应该是splice(index, 1).