Skip to content

Instantly share code, notes, and snippets.

@k0d3d
Last active August 29, 2015 14:27
Show Gist options
  • Save k0d3d/168b78606a9b457dcd12 to your computer and use it in GitHub Desktop.
Save k0d3d/168b78606a9b457dcd12 to your computer and use it in GitHub Desktop.
sample service
//app.config(function($stateProvider, $urlRouterProvider.......
//........
.state('files', {
url: '/files',
views: {
//adapt to fit your application
'cabinetContent' :{
templateUrl: 'templates/files.html',
controller: 'FilerCtrl',
resolve: {
//a property that has to be resolved before the
//controller can be instantiated.
//Passing appDBBridge as a service and using the
//selectOneDoc(document_id_object, collectionName).
//document_id_object should be an object with an id or _id
//property. the collectionName is always a concatenation of
//the service name and the method that should be executed.
//This returns a resolved promise which can be injected into
//a controller like 'FilerCtrl'
userRootCabinet: function (appDBBridge) {
return appDBBridge.selectOneDoc({}, 'Filer.thisUserFiles');
}
}
}
}
})
app.controller('FilerCtrl', [
'$scope',
'userRootCabinet',
'appDBBridge',
'$timeout',
function($scope, userRootCabinet, appDBBridge, $timeout) {
$scope.userRootCabinet = [];
//UserRootCabinet argument is populated from our resolved property.
//when we defined our state in app.js
if (userRootCabinet) {
$scope.userRootCabinet = _.values(_.omit(userRootCabinet, ['_id', '_rev']));
}
//we bind an event to trigger every time we navigate to this view.
//the appDBBridge.fetchAndSyncDataToScope(document_id, serviceName, arguments)
//check the comments on the method to explain how this works.
//_.values(_.omit(updatedDoc, ['_id', '_rev'])); removes unnecessary properties
//from the response in gotten from executing Filer.thisUserFiles().
$scope.$on('$ionicView.enter', function(){
appDBBridge.fetchAndSyncDataToScope('', 'Filer.thisUserFiles', [])
.then(function (updatedDoc) {
var u = $timeout(function () {
$scope.userRootCabinet = _.values(_.omit(updatedDoc, ['_id', '_rev']));
}, 1000);
$scope.$on('$destroy', function () {
u.cancel();
});
});
});
}]);
app.factory('Filer', ['$http', function($http){
return {
/**
* [thisUserFiles request for files belonging to this user]
* @param {[type]} param
* @param {Function} callback
* @return {[type]}
*/
thisUserFiles : function thisUserFiles (param){
return $http.get('/api/v2/users/files', param)
.then(function(data) {
return data;
}, function (data, status) {
return status;
});
};
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment