window.evoapp.service('modelService', function ($rootScope, $http, $q, $timeout) { //http://wekeroad.com/2013/04/25/models-and-services-in-angular //maps the given record to the correct model. the result is the same record only with the model fields. function convert(modelName, record, action){ var model = evoapp.models[modelName]; if(model == undefined) { throw Error('Model ' + modelName + ' not found!'); } var newData = {}; for(n = 0; n < model.fields.length; n++) { var field = model.fields[n], name = field.name, type = field.type; if(record[name] != null && record[name] != undefined) { var fieldValue = record[name]; //convert from MS date to Date if(type == 'date' && field.dateFormat != undefined) { if(field.dateFormat == 'MS') { if(action == null) { fieldValue = moment(fieldValue).toDate(); //remove client timezone offset var offset = new Date(fieldValue).getTimezoneOffset() / 60; fieldValue = moment(fieldValue).add('hours', offset).toDate(); } else if(action == 'upsert') { //all dates going to server must be ISO8601 fieldValue = moment(fieldValue).format('YYYY-MM-DD'); } } } if(type == 'datetime' && field.dateFormat != undefined) { if(field.dateFormat == 'MS') { if(action == null) { fieldValue = moment(fieldValue).toDate(); //remove client timezone offset var offset = new Date(fieldValue).getTimezoneOffset() / 60; fieldValue = moment(fieldValue).add('hours', offset).toDate(); } else if(action == 'upsert') { //all dates going to server must be ISO8601 fieldValue = moment(fieldValue).format('YYYY-MM-DD HH:mm'); } } } if(type == 'float' && fieldValue != null && fieldValue != undefined) { var inan = isNaN(parseFloat(fieldValue)); if(!inan) { fieldValue = parseFloat(new String(fieldValue).replace(/,/, '.')); } } if(type == 'int' && fieldValue != null && fieldValue != undefined) { var inan = isNaN(parseInt(fieldValue)); if(!inan) { fieldValue = parseInt(fieldValue); } } newData[name] = fieldValue; } else { newData[name] = null; } } return newData; }; var toModel = function(model, record, action){ return convert(model, record, action); }; var collectionToModel = function(model, collection, action){ var newCollection = []; if(collection != null) { $.each(collection, function(index, value) { var record = convert(model, value, action); newCollection.push(record); }); } return newCollection; }; return { toModel: toModel, collectionToModel: collectionToModel }; });