微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – AngularJS $资源和超媒体

我有一个像这样定义的AngularJS $资源:
var Menus = $resource('http://cafe.com/api/menus');

一个RESTful API.所以,当我在Menus上做GET时,我得到了回复

<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)

解决方法

假设您已经从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!

原文地址:https://www.jb51.cc/js/159000.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐