I'm starting to learn a lot of things related to the hybrid apps coding. I decided to go on and use Ionic framework, based on AngularJS (this gives me the occasion to learn it), and use Firebase as my backend solution.
I want to setup a map in my app, so I would locate the user and some points of interests around him. I found out GeoFire existed, so I started working with it.
My problem : I fail in displaying a user's location saved into Firebase. I query it using GeoFire, and get the response (console.log it) but it won't update the scope variable.
Here is the JS code :
myApp.factory("MyLoc", function(){
var firebaseRef = new Firebase("https://myfirebase.firebaseio.com/geofire/");
var geoFire = new GeoFire(firebaseRef);
/* geoFire.set("user_loc", [37.785326, -122.405696]).then(function() {
console.log("Provided key has been added to GeoFire");
}, function(error) {
console.log("Error: " + error);
});*/
return geoFire.get("user_loc").then(function(location) {
if (location === null) {
console.log("Provided key is not in GeoFire");
return 0;
}
else {
console.log("Provided key has a location of " + location);
return location;
}
}, function(error) {
console.log("Error: " + error);
return 0;
});
})
myApp.controller("firstCtrl", function($scope, MyLoc) {
$scope.data = {};
$scope.data.myLoc = MyLoc;
});
The HTML just displays it :
{{data.myLoc}}
Since I'm an Angular N00b, I guess I'm missing something obvious. I guess I should use a promise or something similar, just can't figure out how ! Can someone help me, please ? :)
Thank you very much bros !
[UPDATE]
Okay so, here is the answer to the first question !
MyLoc.then(function(data){
$scope.data.myLoc = data;
$scope.$apply();
});
However I had to use
$scope.$apply();
for the HTML to display it, apparently it doesn't updates right away. Do you have any idea why ? I understand Angular has to be notified of a change for it to display, as explained very nicely here : http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
What I don't understand, is why it's the case here ? Why is Angular unaware of the change ?
Thanks again !
then
can and will fire at any moment. So Angular has no knowledge of it, unless you tell it. Don't take my or anyone's word for that though: just set a breakpoint on the line$scope.data.myLoc
and check the stack trace, it is very likely to be different than what you expect it to be. – Alleged