Skip to content

Instantly share code, notes, and snippets.

@anantn
Created April 3, 2013 19:21
Show Gist options
  • Save anantn/5304404 to your computer and use it in GitHub Desktop.
Save anantn/5304404 to your computer and use it in GitHub Desktop.
An example showing the use of angular $q promises to authenticate a Firebase session and then writing data.
<html ng-app="test">
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js"></script>
<script type="text/javascript" src="https://cdn.firebase.com/v0/firebase.js"></script>
</head>
<body ng-controller="Test">
<script typ="text/javascript">
function TestController($scope, $q) {
this._q = $q;
this._scope = $scope;
this.auth_token = "tAN8DtyE5BQshfbEK4mOMBEAnt3RLjjIIFl565Fe";
}
TestController.prototype = {
ref: function(path) {
var self = this;
var deferred = this._q.defer();
var ref = new Firebase("https://stackpad.firebaseio.com" + path);
ref.auth(self.auth_token, function(err) {
if (!err) {
console.log("Login succeeded");
deferred.resolve(ref);
self._scope.$apply();
} else {
console.log("Login failed " + err);
deferred.reject(err);
self._scope.$apply();
}
});
return deferred.promise;
},
set: function(ref, data) {
ref.set(data, function() {
console.log("Set completed!");
});
}
};
angular.module("test", []).controller("Test", function($scope, $q) {
var ct = new TestController($scope, $q);
var promise = ct.ref("/data");
promise.then(function(ref) {
ct.set(ref, "Hello World!");
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment