Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $resource and hypermedia

I have an AngularJS $resource defined like this:

var Menus = $resource('http://cafe.com/api/menus');

and a RESTful API. So when I do a GET on Menus I get this back:

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

Question is, how do I delete menu 2? (given that it has its own hypermedia link: http://cafe.com/api/menus/2)

like image 443
Greg Avatar asked Nov 13 '12 08:11

Greg


1 Answers

Assuming that you have gone from the XML to an Angular-managed array of JavaScript objects, you can use this to render your objects:

<tr ng-repeat="cafe in cafes">
    <td>{{cafe.name}}</td>
    <td>
        <button class="btn" ng-click="deleteCafe($index, cafe)">Delete</button>
    </td>
</tr>

and in your controller you can do this:

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

Look, no client-side creation of URLs! :)

update: fixed a bug in the splice command, was splice(index, index), but should be splice(index, 1).

like image 50
Trygve Laugstøl Avatar answered Sep 23 '22 11:09

Trygve Laugstøl