Question

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)

Was it helpful?

Solution

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

OTHER TIPS

If your REST service returns JSON to angular and the JSON include the menu ID in the returned data.

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();
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top