Skip to content

Instantly share code, notes, and snippets.

@Im0rtality
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save Im0rtality/9427899 to your computer and use it in GitHub Desktop.

Select an option

Save Im0rtality/9427899 to your computer and use it in GitHub Desktop.
Models in AngularJS

Models implementation in AngularJS framework

Model's hierarchy

Star has one StarType
Star has one StarSize
Star has many Planets
Planet has one PlanetType
Planet has one PlanetSize
Planet has many Buildings
Building has one BuildingType

TODO

  • Refactor code so developer only needs to define models as set of values (avoid overwriting functions)
  • Drop utils.inherit entirely
  • Figure out how to add model actions nicely
angular
.module('myApp.model.BaseModel', [])
.factory('BaseModel', ['$injector', 'CacheService', function ($injector, ModelStorage) {
'use strict';
function BaseModel() {}
BaseModel.prototype = {
$meta: {
name: 'BaseModel',
cached: false,
has: {}
},
getName: function () {
return this.$meta.name;
},
setData: function (data) {
angular.extend(this, data);
this.decorate();
},
get: function (id) {
var scope, promise;
scope = this;
promise = ModelStorage.get(this, id);
promise.then(function (data) {
scope.setData(data.original);
});
return promise;
},
isCached: function () {
return this.$meta.cached;
},
decorate: function () {
var scope = this;
angular.forEach(this.$meta.has, function (stub, modelName) {
var fieldName, model;
model = $injector.get(modelName);
//noinspection JSHint
model = new model();
fieldName = stub.field ? stub.field : modelName;
if (stub.many) {
scope[fieldName] = [];
angular.forEach(scope[stub.many], function (child) {
var childObj;
childObj = angular.copy(model);
childObj.get(child[stub.id]);
scope[fieldName].push(childObj);
});
} else {
scope[fieldName] = model;
scope[fieldName].get(scope[stub.id]);
}
});
}
};
return BaseModel;
}]);
angular
.module('myApp.model.Star', [])
.factory('Star', ['BaseModel', function (BaseModel) {
'use strict';
function Star() {}
Star.prototype = angular.copy(BaseModel.prototype);
angular.extend(Star.prototype.$meta, {
name: 'Star',
has: {
StarType: {id: 'type'},
StarSize: {id: 'size'},
Planet: {many: 'planets', id: 'id', field: 'Planets'}
}
});
return Star;
}]);
angular
.module('myApp.model.StarType', [])
.factory('StarType', ['BaseModel', function (BaseModel) {
'use strict';
function StarType() {}
StarType.prototype = angular.copy(BaseModel.prototype);
angular.extend(StarType.prototype.$meta, {
name: 'StarType'
});
return StarType;
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment