Escrevendo patcher de função dinâmica para REST api no serviço angularjs

Neste exemplo, estou mostrando como implemento $ rootScope. $ Apply () para cada chamada de API REST.
Este é apenas um exemplo de como você pode estender seus retornos de chamada de função se assumirmos que seu retorno de chamada da API REST está sempre no último lugar da função.

/*** this is just example of some javascript api api ***/
this.api = {
assets
: {
_init
: function () {
//do something here and this will not be patched
},
one
: function (id, callback) {
http
({ data: {id: id}}).success(callback);
},
two
: function (id, callback) {
http
({ data: {id: id}}).success(callback);
}
}
}

var that = this,
/**
* Don't include methods

* @type {Array}

*/

excludeMethods
= [
'_init',
'option'
],
patchObjects
= [ 'assets', 'user'];

Api patcher estende o callback e coloca um $ rootScope. $ Apply (); para cada retorno de chamada de função

/**
* Api patcher

*
@param source
*
@param destionation
*/

function extend(source, destionation) {
var fn = function (i) {
return function () {
var lastIndex = arguments.length - 1,
args
= Array.prototype.slice.call(arguments, 0, lastIndex),
callback
= arguments[lastIndex];
/**
* Patch last one

*/

args
.push(function (data, error) {
if (angular.isFunction(callback)) {
callback
.call(this, data, error);
$rootScope
.$apply();
}
});
/**
* Call the source with new arguments

*/

source
[i].apply(source, args);
}
};
/**
* Loop over method

*/

for (var i in source) {
if (excludeMethods.indexOf(i) === -1) {
if (angular.isFunction(source[i])) {
destionation
[i] = fn(i);
}
}
}
}

/**
* Patch objects

*/

patchObjects
.forEach(function (value) {
that
[value] = {}; // initialize
extend
(that.api[value], that[value]);
});

O serviço terá um método como o qual você chamará no controlador

myApiService.assets.one(id, function (data, error) {
$scope
.list = data;
// now you don't need to call $rootScope.$apply(); on each request
});