Question

Is there an equivalent to Backbone's Collection or Ext JS's Store in Angular JS? I'm learning about $resource, but not quite getting this aspect.

Controller

// This is the "collection" I'm interested in.
$scope.foos = [];

// Foo is a $resource.
Foo.query(function (foos) {

  // This works, but is there a smarter "collection" object?
  $scope.foos = foos;
});

$scope.createFoo = function (data) {
  var foo = new Foo(data);

  foo.$save(function (shinyNewFoo) {
    $scope.foos.unshift(shinyNewFoo);
  });
};

Explanation

In $scope.createFoo I'm making a new Foo, persisting it, then adding it to my poor man's collection, an array. This works and the view is updated correctly, but I'm too lazy for this. Ideally, I'd like to have a "collection" I can add to and remove from that will automatically POST/DELETE. Maybe something like the following.

Pretend Implementation

$scope.fooCollection = new CoolCollection({
  // specify the type of resources this collection will contain
  itemsResource: Foo
});

// Creates new Foo, saves, adds to collection.
$scope.fooCollection.add(data);

Does something like this exist? The $resource docs mention a collection, but I didn't really get it. This answer seemed promising, but didn't explain the collection idea. Am I missing something or just not thinking about this the Angular way?


Addendum

In the MEAN.io boilerplate, the article controller suggests that the "collection" is managed manually (see the splice below).

$scope.remove = function(article) {
    if (article) {
        article.$remove();

        for (var i in $scope.articles) {
            if ($scope.articles[i] === article) {
                $scope.articles.splice(i, 1);
            }
        }
    } else {
        $scope.article.$remove();
        $location.path('articles');
    }
};

If this elusive "collection" existed, I suppose they would have used it. Instead, they're managing an array manually.

Était-ce utile?

La solution

AngularJS does not define any kind of structured data model. This part is entirely up to you.

The $resource service is just a wrapper on top of the lower-level $http service; it defines a high level way to fetch your data from the server and has little to do with how you structure your data on the frontend.

If a more sophisticated frontend data model is required by your application, you should investigate other JS libraries or roll your own. However, angular's singleton services and powerful two-way data binding make this unnecessary for most small/medium applications.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top