Skip to content

Instantly share code, notes, and snippets.

@dmgig
Last active March 25, 2016 18:31
Show Gist options
  • Save dmgig/af920c1212573da9ef8b to your computer and use it in GitHub Desktop.
Save dmgig/af920c1212573da9ef8b to your computer and use it in GitHub Desktop.
Sample Angular Factory
/**
* https://medium.com/opinionated-angularjs/angular-model-objects-with-javascript-classes-2e6a067c73bc
*/
.factory('Customer', function ($http, $log, KeyMap) {
var Customer = function(OtherCustomer){
this.id = OtherCustomer.id;
this.keymap = KeyMap;
this.comparisons = [];
this.working = false;
}
/**
* retrieve the related record, and use the keymap to compare the two objects.
* pack the "comparisons" variable with { keyA, valueA, equality, valB, keyB }
*/
Customer.prototype.compare = function(){
var CUST = this;
var comparisons = [];
CUST.working = true;
$http
.post('data/account.php', { "id": CUST.id })
.success(function(response){
CUST.comparisons = [];
CUST.B = response.data;
angular.forEach(CUST.A, function(value, key) {
var altkey = CUST.keymap.getAltKey(key, 'A', 'B');
var comparison = {
keyA = key;
valA = value;
keyB = altkey;
valB = CUST.B[altkey];
equality = CUST.checkEquality( comparison.valA, comparison.valB );
};
CUST.comparisons.push(comparison);
});
CUST.working = false;
})
.error(function(){
alert('could not get account ' + id); CUST.working = false;
});
}
/**
* a loose equality check, but will also have to make up for datatype differences.
*/
Customer.prototype.checkEquality = function(a, b){
if(a == null) a = '';
if(b == null) b = '';
return ( a == b ? true : false );
}
return Customer;
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment