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?