4

I've got angular set up to talk to a collection of objects with REST, using the $resource framework. Something like this:

angular.module('ngBooks', ['ngResource'])

    .factory('Book', ['$resource', function ($resource) {
        return $resource('/books/:id', {}, {
            all: {method: 'GET', url: '/books/', isArray: true},
            get: {method: 'GET', params: {id: '@id'}},
            delete: {method: 'DELETE', params: {id: '@id'}}
        });
    }])

    .controller(
        'ngBookController',
        ['$scope', '$http', 'Book', function ($scope, $http, Book) {
            $scope.books = Book.all();
        }]
    );

So that's really nice. I've now got special methods on all the book objects in my scope, so I can do a nice dynamic table of them like this:

<div ng-app="ngBooks" ng-controller="ngBookController as controller">
  <table>
    <thead><tr><th>Title</th><th>Author</th></tr></thead>
    <tbody>
      <tr ng-repeat="book in books">
        <td>{{ book.title }}</td>
        <td>{{ book.author }}</td>
        <td><button ng-click="book.$delete()">Delete</button></td>
      </tr>
    <tr ng-show="!books.length"><td colspan="3"><i>No books here.</i> </td></tr>
  </table>
  </div>
  <button ng-click="???">Refresh books list</button>
</div>

Question: How do I make a button to refresh the list of books? I know I can "roll my own" in the controller, something like this:

        $scope.refresh = function () {
            $scope.books = Book.all();
        };

And then use

  <button ng-click="refresh()">Refresh books list</button>

But I feel like there should be some sort of "magic" way of doing it, right? After all, all my book objects magically have book.$delete()... I want to be able to do something like:

  <button ng-click="books.$all()">Refresh books list</button>

Is there something like that? Does the magical angular two-way data binding also work for arrays of ngResource objects?

hwjp
  • 15,359
  • 7
  • 71
  • 70
  • I do not get why `books.all()` or `books.query()` are less magic than `book.$delete()` ... use them directly in the on-click directive, no? It cannot be more simple ... – M'sieur Toph' Mar 09 '15 at 13:25
  • there is no such thing as books.all() or books.query(), as far as I can tell? – hwjp Mar 09 '15 at 16:39
  • My mistake, I thought about `Book.all()` or `Book.query()`. There is no simpler method. By the way, if you manage your initial collection correctly (using right HTTP method on the right place), your collection is always up-to-date ... And if you need to synchronize it again with a server collection, you have to go through a refresh of your scope, as you told. And it is completely different from resource manipulation so it logically takes place in the controller or link block, via a refresh() function and not in the DOM. – M'sieur Toph' Mar 09 '15 at 20:38

0 Answers0