Navigation Menu

Skip to content

tomkuk/angular-collection

Repository files navigation

AngularCollection

js-standard-style npm version Bower version npm downloads License

Build Status Code Climate Test Coverage Dependency Status devDependency Status

angular-collection.js

Description

AngularCollection is a collection module for AngularJS.

Installation

angular-collection is a bower component you should be able to install it by running:

bower install angular-collection

or if you already have a bower based project you can add angular-collection to your dependency list in bower.json

 "dependencies": {
    ...
    "angular-collection": "0.x.x"
    ...
  }

API

  • add(obj, options)

  • addAll(array, options)

  • sort()

  • get(obj | id)

  • update(obj)

  • remove(obj)

  • removeAll()

  • last()

  • at(index)

  • size()

  • all()

Usage

Specify dependencies

var app = angular.module('myApp', ['ngCollection']);

Define new factory

app.factory("TodoCollection", function($collection){
	var TodoCollection = $collection;

	return TodoCollection;
})

Get collection instance

var todos = TodoCollection.getInstance();

Add new records

_id property will be generated and attached to each new record.

todos.add({ title: "todo1" });
todos.add({ title: "todo2" });
todos.add({ title: "todo0" }, {index: 0});

Get a single record

Get a record from the collection, specified by an id or by passing in a record.

	var todo = todos.get(10);

Update a single record

If a record is already in the collection, its attributes will be merged.

	todos.update({ id: 1, title: 'todos3' });

Remove a record from the collection

	todos.remove({ id: 1, title: 'todos3' });

Get a single record, spcified by index

	todos.at(1);

Sort records as they are added to collection

Sort the collection by title descending each time you call add()

	var todos = $collection.getInstance({comparator: "-title"});
	todos.add({ title: "todo1" });		// performs sort
	todos.add({ title: "todo2" });		// performs sort

Sort records on demand

Sorts the collection by title descending but only when sort() is called

	var todos = $collection.getInstance();
	todos.add({ title: "todo1" });
	todos.add({ title: "todo2" });
	todos.sort('-title');			// performs sort

Options

You can pass a single parameter to getInstance to specify additional options.

var todos = TodoCollection.getInstance(options);

Currently the only options available are idAttribute and comparator.

var todos = TodoCollection.getInstance({idAttribute: 'id', comparator: '-created_at'});

Contributors:

License:

The MIT License

About

A collection module for AngularJS

Resources

Stars

Watchers

Forks

Packages

No packages published