如何刷新角度资源上的查询数组

时间:2014-10-22 10:25:01

标签: angularjs ngresource

我已经设置了角度来使用$ resource框架与REST对象集合进行交谈。像这样:

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

所以这真的很好。我现在在我的范围内的所有书籍对象上都有特殊的方法,所以我可以像这样对它们做一个很好的动态表:

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

问题:如何制作按钮来刷新图书清单?我知道我可以在控制器中“滚动自己”,如下所示:

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

然后使用

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

但我觉得应该有某种“神奇”的做法,对吧?毕竟,我的所有book个对象都神奇地拥有book.$delete() ...我希望能够做到这样的事情:

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

有类似的东西吗?神奇的角度双向数据绑定是否也适用于ngResource对象的数组?

0 个答案:

没有答案