The Basics - swimlane/angular-model-factory GitHub Wiki
Note, this wiki article is under construction and not yet complete. Please come back later
This article outlines the basics and most common use cases of the modelFactory.
Model
Defining a new To define a new Model create an Angular service class and inject the $modelFactory
dependency.
var module = angular.module('services.people', ['modelFactory']);
module.factory('PersonModel', function($modelFactory){
return $modelFactory('api/people');
});
return module;
This is the simplest form of defining a new modelFactory model that can be used to interact with an API exposed at api/people
.
Note: Contrary to most of the Angular style-guides it is suggested to define the name of the model in uppercase. We'll see later why.
Once the model is defined it can be injected into any arbitrary Angular component. You can either call the static methods directly on the model or instantiate it and invoke the instance methods.
function SomeController(PersonModel) {
// invoke a static method
PersonModel.query();
// create an instance
var aPerson = new PersonModel({
name: 'Juri'
});
// set additional properties
aPerson.age = 29;
}
More on the available static and per-instance methods in the following sections.
What you'll get out of the box
First of all, there's a set of build-in functions that cover most basic use cases.
Static methods are:
PersonModel.query()
- executes a/api/people
call and expects an array of Person as the result.PersonModel.get(123)
- executes a/api/people/123
call and expects a single instance of a Person.
Per-instance methods are:
somePerson.$save()
- executes aPOST /api/people
orPUT /api/people/{id}
depending on whether we have a new or an existing model (id property is > 0). The body contains the JSON serialized data.somePerson.$destroy()
- executes aDELETE /api/people/{id}
having no data in the body. The intent is obviously to permanently delete a person.
All of these methods are promise based:
var somePerson.$save()
.then(function(result) {
// the saved person, although it is automatically updated
// onto the existing somePerson instance.
})
.catch(function(){
// something bad happened and you may want to tell the user
});