| angular.module('myApp') | |
| .factory('Model', function Model(Resource) { | |
| function Model(mdl){ | |
| var model = mdl || {}; | |
| // attributes of the class goes here... | |
| this.attr = model.attr; | |
| } | |
| var instantiate = function(col, callback) { | |
| var collection = (Array.isArray(col)) ? col : [col]; | |
| collection.map(function(el, index) { | |
| collection[index] = new Model(el); | |
| }); | |
| callback(collection); | |
| } | |
| // You can get the collection retreived directly from the Model or callback | |
| Model.collection = []; | |
| // You can access the instance retrieved from the model or callback | |
| Model.instance = {}; | |
| // General method to retreive a collection from an endpoint | |
| Model.findCollection = function(params, callback) { | |
| Resource.query(params, function(data) { | |
| instantiate(data, function(collection) { | |
| Model.collection = data; | |
| callback(data); | |
| }); | |
| }); | |
| } | |
| // not a real "facade" but simplifies the queries to the endpoint. | |
| Model.findCustomCollection = function(callback) { | |
| var params = { /* custom params here... */ }; | |
| Model.findCollection(params, function(data) { | |
| callback(data); | |
| }); | |
| } | |
| // retreives a single instance, you can access it through the Model or cb | |
| Model.find = function(id, callback) { | |
| Resource.get({ id: id }, function(data) { | |
| Model.instance = new Model(data) | |
| callback(Model.instance); | |
| }); | |
| } | |
| Model.prototype.save = function(callback) { | |
| model = new Resource(this.model); | |
| model.$save(callback()); | |
| } | |
| Model.prototype.update = function(callback) { | |
| model = new Resource(this.model); | |
| model.$update(callback()); | |
| } | |
| Model.prototype.delete = function(callback) { | |
| model = new Resource(this.model); | |
| model.$remove(callback()); | |
| } | |
| Model.prototype.customMethod = function(params) { | |
| // code here | |
| } | |
| return Model; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment