Last active
February 7, 2017 18:16
-
-
Save r3wt/5955e280e78a1e254e9d800ba26dc8bd to your computer and use it in GitHub Desktop.
a helper for angularfire making things easier.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module('myApp') | |
.factory('$db',['$firebaseObject','$firebaseArray','$q',function($firebaseObject,$firebaseArray,$q){ | |
function $db( type, id ){ | |
var ref = firebase.database().ref(type).child(id); | |
var obj = $firebaseObject(ref); | |
return $q(function(resolve,reject){ | |
obj.$loaded().then(function(){ | |
resolve(obj); | |
}).catch(reject); | |
}); | |
} | |
//todo maybe add a helper for firebase arrays. | |
$db.array = function( typeOrRef ){ | |
if(typeOrRef instanceof firebase.database.Reference){ | |
var ref = typeOrRef; | |
}else{ | |
var ref = firebase.database().ref(typeOrRef); | |
} | |
var a = $firebaseArray(ref); | |
return $q(function(resolve,reject){ | |
a.$loaded().then(function(){ | |
resolve(a); | |
}).catch(reject); | |
}); | |
}; | |
return $db; | |
}]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module('myApp') | |
.controller('BlogCtrl',function($scope,$db,$stateParams){ | |
//single post as object | |
$db('blogposts',$stateParams.id).then(function(blogPost){ | |
$scope.blogPost = blogPost; | |
}).catch(function(err){ | |
//do something with err | |
}); | |
//array of posts | |
$db.array('blogposts').then(function(blogPosts){ | |
$scope.blogPosts = blogPosts; | |
}); | |
//array using custom ref or query | |
$db.array( firebase.database().ref('blogposts') ).then(function(blogPosts){ | |
$scope.blogPosts = blogPosts; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment