Skip to content

Instantly share code, notes, and snippets.

@devniel
Forked from ruiwen/fb-angular.js
Last active July 29, 2023 04:54
Show Gist options
  • Save devniel/5846169 to your computer and use it in GitHub Desktop.
Save devniel/5846169 to your computer and use it in GitHub Desktop.
// Facebook SDK
angular.module('facebook', [])
.directive('fb', ['$FB', function($FB) {
return {
restrict: "E",
replace: true,
template: "<div id='fb-root'></div>",
compile: function(tElem, tAttrs) {
return {
post: function(scope, iElem, iAttrs, controller) {
var fbAppId = iAttrs.appId || '';
var fb_params = {
appId: iAttrs.appId || "",
cookie: iAttrs.cookie || true,
status: iAttrs.status || true,
xfbml: iAttrs.xfbml || true
};
// Setup the post-load callback
window.fbAsyncInit = function() {
$FB._init(fb_params);
if('fbInit' in iAttrs) {
iAttrs.fbInit();
}
};
(function(d, s, id, fbAppId) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk', fbAppId));
}
}
}
};
}])
.factory('$FB', ['$rootScope', function($rootScope) {
var fbLoaded = false;
// Our own customisations
var _fb = {
loaded: fbLoaded,
isLoaded : function(){
return this.loaded;
},
authenticated : false,
isAuthenticated : function(){
return this.authenticated;
},
_init: function(params) {
self = this;
if(window.FB) {
// FIXME: Ugly hack to maintain both window.FB
// and our AngularJS-wrapped $FB with our customisations
angular.extend(window.FB, this);
angular.extend(this, window.FB);
// Set the flag
this.loaded = true;
// Initialise FB SDK
window.FB.init(params);
window.FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
self.authenticated = true;
}
});
if(!$rootScope.$$phase) {
$rootScope.$apply();
}
}
}
}
return _fb;
}]);
<!DOCTYPE html>
<html ng-app='app'>
<head></head>
<body>
<fb app-id='123123'></fb>
</body>
</html>
function UserCtrl(
$scope,
$FB) {
$scope.$watch(function() {
return $FB.isLoaded()
},function(value){
console.log("VALUE",value);
// It needs authentication, this won't work.
if(value){
$scope.facebook_friends = $FB.api('/me/friends', function(response) {
$scope.facebook_friends = response.data;
});
}
},true);
$scope.$watch(function() {
return $FB.isAuthenticated()
},function(value){
console.log("VALUE isAuthenticated",value);
// YEP, this will work.
if(value){
$scope.facebook_friends = $FB.api('/me/friends', function(response) {
$scope.facebook_friends = response.data;
console.log("FRIENDS",response);
});
}
},true);
@theraaz
Copy link

theraaz commented Apr 10, 2014

@fmalk it would be great if you share your solution as well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment